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),
230 mPipelineCached(false)
232 if(blendingBitmask != 0u)
234 mBlendingOptions.SetBitmask(blendingBitmask);
237 mBlendingOptions.SetBlendColor(blendColor);
240 void Renderer::Initialize(Graphics::Controller& graphicsController, ProgramCache& programCache, Render::ShaderCache& shaderCache, Render::UniformBufferManager& uniformBufferManager, Render::PipelineCache& pipelineCache)
242 mGraphicsController = &graphicsController;
243 mProgramCache = &programCache;
244 mShaderCache = &shaderCache;
245 mUniformBufferManager = &uniformBufferManager;
246 mPipelineCache = &pipelineCache;
249 Renderer::~Renderer()
251 // Reset old pipeline
252 if(DALI_LIKELY(mPipelineCached))
254 mPipelineCache->ResetPipeline(mPipeline);
255 mPipelineCached = false;
259 void Renderer::operator delete(void* ptr)
261 GetRenderRendererMemoryPool().FreeThreadSafe(static_cast<Renderer*>(ptr));
264 Renderer* Renderer::Get(RendererKey::KeyType rendererKey)
266 return GetRenderRendererMemoryPool().GetPtrFromKey(rendererKey);
269 void Renderer::SetGeometry(Render::Geometry* geometry)
271 mGeometry = geometry;
274 void Renderer::SetDrawCommands(Dali::DevelRenderer::DrawCommand* pDrawCommands, uint32_t size)
276 mDrawCommands.clear();
277 mDrawCommands.insert(mDrawCommands.end(), pDrawCommands, pDrawCommands + size);
280 void Renderer::BindTextures(Graphics::CommandBuffer& commandBuffer, Vector<Graphics::Texture*>& boundTextures)
282 uint32_t textureUnit = 0;
284 auto textures(mRenderDataProvider->GetTextures());
285 auto samplers(mRenderDataProvider->GetSamplers());
287 std::vector<Graphics::TextureBinding> textureBindings;
289 if(textures != nullptr)
291 const std::uint32_t texturesCount(static_cast<std::uint32_t>(textures->Count()));
292 textureBindings.reserve(texturesCount);
294 for(uint32_t i = 0; i < texturesCount; ++i) // not expecting more than uint32_t of textures
296 if((*textures)[i] && (*textures)[i]->GetGraphicsObject())
298 Graphics::Texture* graphicsTexture = (*textures)[i]->GetGraphicsObject();
299 // if the sampler exists,
300 // if it's default, delete the graphics object
301 // otherwise re-initialize it if dirty
303 const Graphics::Sampler* graphicsSampler = samplers ? ((*samplers)[i] ? (*samplers)[i]->GetGraphicsObject()
307 boundTextures.PushBack(graphicsTexture);
308 const Graphics::TextureBinding textureBinding{graphicsTexture, graphicsSampler, textureUnit};
309 textureBindings.push_back(textureBinding);
316 if(!textureBindings.empty())
318 commandBuffer.BindTextures(textureBindings);
322 void Renderer::SetFaceCullingMode(FaceCullingMode::Type mode)
324 mFaceCullingMode = mode;
327 void Renderer::SetBlendingBitMask(uint32_t bitmask)
329 mBlendingOptions.SetBitmask(bitmask);
332 void Renderer::SetBlendColor(const Vector4& color)
334 mBlendingOptions.SetBlendColor(color);
337 void Renderer::SetIndexedDrawFirstElement(uint32_t firstElement)
339 mIndexedDrawFirstElement = firstElement;
342 void Renderer::SetIndexedDrawElementsCount(uint32_t elementsCount)
344 mIndexedDrawElementsCount = elementsCount;
347 void Renderer::EnablePreMultipliedAlpha(bool enable)
349 mPremultipliedAlphaEnabled = enable;
352 void Renderer::SetDepthWriteMode(DepthWriteMode::Type depthWriteMode)
354 mDepthWriteMode = depthWriteMode;
357 void Renderer::SetDepthTestMode(DepthTestMode::Type depthTestMode)
359 mDepthTestMode = depthTestMode;
362 DepthWriteMode::Type Renderer::GetDepthWriteMode() const
364 return mDepthWriteMode;
367 DepthTestMode::Type Renderer::GetDepthTestMode() const
369 return mDepthTestMode;
372 void Renderer::SetDepthFunction(DepthFunction::Type depthFunction)
374 mDepthFunction = depthFunction;
377 DepthFunction::Type Renderer::GetDepthFunction() const
379 return mDepthFunction;
382 void Renderer::SetRenderMode(RenderMode::Type renderMode)
384 mStencilParameters.renderMode = renderMode;
387 RenderMode::Type Renderer::GetRenderMode() const
389 return mStencilParameters.renderMode;
392 void Renderer::SetStencilFunction(StencilFunction::Type stencilFunction)
394 mStencilParameters.stencilFunction = stencilFunction;
397 StencilFunction::Type Renderer::GetStencilFunction() const
399 return mStencilParameters.stencilFunction;
402 void Renderer::SetStencilFunctionMask(int stencilFunctionMask)
404 mStencilParameters.stencilFunctionMask = stencilFunctionMask;
407 int Renderer::GetStencilFunctionMask() const
409 return mStencilParameters.stencilFunctionMask;
412 void Renderer::SetStencilFunctionReference(int stencilFunctionReference)
414 mStencilParameters.stencilFunctionReference = stencilFunctionReference;
417 int Renderer::GetStencilFunctionReference() const
419 return mStencilParameters.stencilFunctionReference;
422 void Renderer::SetStencilMask(int stencilMask)
424 mStencilParameters.stencilMask = stencilMask;
427 int Renderer::GetStencilMask() const
429 return mStencilParameters.stencilMask;
432 void Renderer::SetStencilOperationOnFail(StencilOperation::Type stencilOperationOnFail)
434 mStencilParameters.stencilOperationOnFail = stencilOperationOnFail;
437 StencilOperation::Type Renderer::GetStencilOperationOnFail() const
439 return mStencilParameters.stencilOperationOnFail;
442 void Renderer::SetStencilOperationOnZFail(StencilOperation::Type stencilOperationOnZFail)
444 mStencilParameters.stencilOperationOnZFail = stencilOperationOnZFail;
447 StencilOperation::Type Renderer::GetStencilOperationOnZFail() const
449 return mStencilParameters.stencilOperationOnZFail;
452 void Renderer::SetStencilOperationOnZPass(StencilOperation::Type stencilOperationOnZPass)
454 mStencilParameters.stencilOperationOnZPass = stencilOperationOnZPass;
457 StencilOperation::Type Renderer::GetStencilOperationOnZPass() const
459 return mStencilParameters.stencilOperationOnZPass;
462 void Renderer::Upload()
464 mGeometry->Upload(*mGraphicsController);
467 bool Renderer::Render(Graphics::CommandBuffer& commandBuffer,
468 BufferIndex bufferIndex,
469 const SceneGraph::NodeDataProvider& node,
470 const Matrix& modelMatrix,
471 const Matrix& modelViewMatrix,
472 const Matrix& viewMatrix,
473 const Matrix& projectionMatrix,
476 Vector<Graphics::Texture*>& boundTextures,
477 const Dali::Internal::SceneGraph::RenderInstruction& instruction,
480 // Before doing anything test if the call happens in the right queue
481 if(mDrawCommands.empty() && queueIndex > 0)
486 // Check if there is render callback
489 if(!mRenderCallbackInput)
491 mRenderCallbackInput = std::unique_ptr<RenderCallbackInput>(new RenderCallbackInput);
494 Graphics::DrawNativeInfo info{};
495 info.api = Graphics::DrawNativeAPI::GLES;
496 info.callback = &static_cast<Dali::CallbackBase&>(*mRenderCallback);
497 info.userData = mRenderCallbackInput.get();
499 // Set storage for the context to be used
500 info.glesNativeInfo.eglSharedContextStoragePointer = &mRenderCallbackInput->eglContext;
501 info.reserved = nullptr;
503 auto& textureResources = mRenderCallback->GetTextureResources();
505 if(!textureResources.empty())
507 mRenderCallbackTextureBindings.clear();
508 mRenderCallbackInput->textureBindings.resize(textureResources.size());
510 for(auto& texture : textureResources)
512 auto& textureImpl = GetImplementation(texture);
513 auto graphicsTexture = textureImpl.GetRenderTextureKey()->GetGraphicsObject();
515 auto properties = mGraphicsController->GetTextureProperties(*graphicsTexture);
517 mRenderCallbackTextureBindings.emplace_back(graphicsTexture);
518 mRenderCallbackInput->textureBindings[i++] = properties.nativeHandle;
520 info.textureCount = mRenderCallbackTextureBindings.size();
521 info.textureList = mRenderCallbackTextureBindings.data();
524 // pass render callback input
525 mRenderCallbackInput->size = size;
526 mRenderCallbackInput->projection = projectionMatrix;
528 MatrixUtils::MultiplyProjectionMatrix(mRenderCallbackInput->mvp, modelViewMatrix, projectionMatrix);
531 commandBuffer.DrawNative(&info);
536 std::vector<DevelRenderer::DrawCommand*> commands;
537 for(auto& cmd : mDrawCommands)
539 if(cmd.queue == queueIndex)
541 commands.emplace_back(&cmd);
545 // Have commands but nothing to be drawn - abort
546 if(!mDrawCommands.empty() && commands.empty())
552 if(!mDrawCommands.empty())
554 blend = (commands[0]->queue != DevelRenderer::RENDER_QUEUE_OPAQUE) && blend;
558 ShaderDataPtr shaderData = mRenderDataProvider->GetShader().GetShaderData();
560 Program* program = Program::New(*mProgramCache,
562 *mGraphicsController);
565 DALI_LOG_ERROR("Failed to get program for shader at address %p.\n", reinterpret_cast<const void*>(&mRenderDataProvider->GetShader()));
569 // If program doesn't have Gfx program object assigned yet, prepare it.
570 if(!program->GetGraphicsProgramPtr())
572 const std::vector<char>& vertShader = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::VERTEX_SHADER);
573 const std::vector<char>& fragShader = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER);
574 Dali::Graphics::Shader& vertexShader = mShaderCache->GetShader(
576 Graphics::PipelineStage::VERTEX_SHADER,
577 shaderData->GetSourceMode());
579 Dali::Graphics::Shader& fragmentShader = mShaderCache->GetShader(
581 Graphics::PipelineStage::FRAGMENT_SHADER,
582 shaderData->GetSourceMode());
584 std::vector<Graphics::ShaderState> shaderStates{
585 Graphics::ShaderState()
586 .SetShader(vertexShader)
587 .SetPipelineStage(Graphics::PipelineStage::VERTEX_SHADER),
588 Graphics::ShaderState()
589 .SetShader(fragmentShader)
590 .SetPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER)};
592 auto createInfo = Graphics::ProgramCreateInfo();
593 createInfo.SetShaderState(shaderStates);
594 auto graphicsProgram = mGraphicsController->CreateProgram(createInfo, nullptr);
595 program->SetGraphicsProgram(std::move(graphicsProgram));
598 // Prepare the graphics pipeline. This may either re-use an existing pipeline or create a new one.
599 auto& pipeline = PrepareGraphicsPipeline(*program, instruction, node, blend);
601 commandBuffer.BindPipeline(pipeline);
603 BindTextures(commandBuffer, boundTextures);
605 std::size_t nodeIndex = BuildUniformIndexMap(bufferIndex, node, size, *program);
607 WriteUniformBuffer(bufferIndex, commandBuffer, program, instruction, node, modelMatrix, modelViewMatrix, viewMatrix, projectionMatrix, size, nodeIndex);
609 bool drawn = false; // Draw can fail if there are no vertex buffers or they haven't been uploaded yet
610 // @todo We should detect this case much earlier to prevent unnecessary work
612 // Reuse latest bound vertex attributes location, or Bind buffers to attribute locations.
613 if(ReuseLatestBoundVertexAttributes(mGeometry) || mGeometry->BindVertexAttributes(commandBuffer))
615 if(mDrawCommands.empty())
617 drawn = mGeometry->Draw(*mGraphicsController, commandBuffer, mIndexedDrawFirstElement, mIndexedDrawElementsCount);
621 for(auto& cmd : commands)
623 drawn |= mGeometry->Draw(*mGraphicsController, commandBuffer, cmd->firstIndex, cmd->elementCount);
629 // BindVertexAttributes failed. Reset cached geometry.
630 ReuseLatestBoundVertexAttributes(nullptr);
636 std::size_t Renderer::BuildUniformIndexMap(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program)
638 // Check if the map has changed
639 DALI_ASSERT_DEBUG(mRenderDataProvider && "No Uniform map data provider available");
641 const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMapDataProvider();
642 const SceneGraph::CollectedUniformMap& uniformMap = uniformMapDataProvider.GetCollectedUniformMap();
643 const SceneGraph::UniformMap& uniformMapNode = node.GetNodeUniformMap();
647 // Usual case is to only have 1 node, however we do allow multiple nodes to reuse the same
648 // renderer, so we have to cache uniform map per render item (node / renderer pair).
650 // Specially, if node don't have uniformMap, we mark nodePtr as nullptr.
651 // So, all nodes without uniformMap will share same UniformIndexMap, contains only render data providers.
652 const auto nodePtr = uniformMapNode.Count() ? &node : nullptr;
654 const auto nodeChangeCounter = nodePtr ? uniformMapNode.GetChangeCounter() : 0;
655 const auto renderItemMapChangeCounter = uniformMap.GetChangeCounter();
657 auto iter = std::find_if(mNodeIndexMap.begin(), mNodeIndexMap.end(), [nodePtr](RenderItemLookup& element) { return element.node == nodePtr; });
659 std::size_t renderItemMapIndex;
660 if(iter == mNodeIndexMap.end())
662 renderItemMapIndex = mUniformIndexMaps.size();
663 RenderItemLookup renderItemLookup;
664 renderItemLookup.node = nodePtr;
665 renderItemLookup.index = renderItemMapIndex;
666 renderItemLookup.nodeChangeCounter = nodeChangeCounter;
667 renderItemLookup.renderItemMapChangeCounter = renderItemMapChangeCounter;
668 mNodeIndexMap.emplace_back(renderItemLookup);
671 mUniformIndexMaps.resize(mUniformIndexMaps.size() + 1);
675 renderItemMapIndex = iter->index;
677 updateMaps = (nodeChangeCounter != iter->nodeChangeCounter) ||
678 (renderItemMapChangeCounter != iter->renderItemMapChangeCounter) ||
679 (mUniformIndexMaps[renderItemMapIndex].size() == 0);
681 iter->nodeChangeCounter = nodeChangeCounter;
682 iter->renderItemMapChangeCounter = renderItemMapChangeCounter;
685 if(updateMaps || mShaderChanged)
687 // Reset shader pointer
688 mShaderChanged = false;
690 const uint32_t mapCount = uniformMap.Count();
691 const uint32_t mapNodeCount = uniformMapNode.Count();
693 mUniformIndexMaps[renderItemMapIndex].clear(); // Clear contents, but keep memory if we don't change size
694 mUniformIndexMaps[renderItemMapIndex].resize(mapCount + mapNodeCount);
696 // Copy uniform map into mUniformIndexMap
697 uint32_t mapIndex = 0;
698 for(; mapIndex < mapCount; ++mapIndex)
700 mUniformIndexMaps[renderItemMapIndex][mapIndex].propertyValue = uniformMap.mUniformMap[mapIndex].propertyPtr;
701 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformName = uniformMap.mUniformMap[mapIndex].uniformName;
702 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHash = uniformMap.mUniformMap[mapIndex].uniformNameHash;
703 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHashNoArray = uniformMap.mUniformMap[mapIndex].uniformNameHashNoArray;
704 mUniformIndexMaps[renderItemMapIndex][mapIndex].arrayIndex = uniformMap.mUniformMap[mapIndex].arrayIndex;
707 for(uint32_t nodeMapIndex = 0; nodeMapIndex < mapNodeCount; ++nodeMapIndex)
709 auto hash = uniformMapNode[nodeMapIndex].uniformNameHash;
710 auto& name = uniformMapNode[nodeMapIndex].uniformName;
712 for(uint32_t i = 0; i < mapCount; ++i)
714 if(mUniformIndexMaps[renderItemMapIndex][i].uniformNameHash == hash &&
715 mUniformIndexMaps[renderItemMapIndex][i].uniformName == name)
717 mUniformIndexMaps[renderItemMapIndex][i].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
725 mUniformIndexMaps[renderItemMapIndex][mapIndex].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
726 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformName = uniformMapNode[nodeMapIndex].uniformName;
727 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHash = uniformMapNode[nodeMapIndex].uniformNameHash;
728 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHashNoArray = uniformMapNode[nodeMapIndex].uniformNameHashNoArray;
729 mUniformIndexMaps[renderItemMapIndex][mapIndex].arrayIndex = uniformMapNode[nodeMapIndex].arrayIndex;
734 mUniformIndexMaps[renderItemMapIndex].resize(mapIndex);
736 return renderItemMapIndex;
739 void Renderer::WriteUniformBuffer(
740 BufferIndex bufferIndex,
741 Graphics::CommandBuffer& commandBuffer,
743 const SceneGraph::RenderInstruction& instruction,
744 const SceneGraph::NodeDataProvider& node,
745 const Matrix& modelMatrix,
746 const Matrix& modelViewMatrix,
747 const Matrix& viewMatrix,
748 const Matrix& projectionMatrix,
750 std::size_t nodeIndex)
753 uint32_t uboOffset{0u};
755 auto& reflection = mGraphicsController->GetProgramReflection(program->GetGraphicsProgram());
757 uint32_t uniformBlockAllocationBytes = program->GetUniformBlocksMemoryRequirements().totalSizeRequired;
759 // Create uniform buffer view from uniform buffer
760 Graphics::UniquePtr<Render::UniformBufferView> uboView{nullptr};
761 if(uniformBlockAllocationBytes)
763 auto uboPoolView = mUniformBufferManager->GetUniformBufferViewPool(bufferIndex);
764 uboView = uboPoolView->CreateUniformBufferView(uniformBlockAllocationBytes);
767 // update the uniform buffer
768 // pass shared UBO and offset, return new offset for next item to be used
769 // don't process bindings if there are no uniform buffers allocated
772 auto uboCount = reflection.GetUniformBlockCount();
773 mUniformBufferBindings.resize(uboCount);
775 std::vector<Graphics::UniformBufferBinding>* bindings{&mUniformBufferBindings};
777 mUniformBufferBindings[0].buffer = uboView->GetBuffer(&mUniformBufferBindings[0].offset);
779 // Write default uniforms
780 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_MATRIX), *uboView, modelMatrix);
781 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::VIEW_MATRIX), *uboView, viewMatrix);
782 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::PROJECTION_MATRIX), *uboView, projectionMatrix);
783 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_VIEW_MATRIX), *uboView, modelViewMatrix);
785 auto mvpUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::MVP_MATRIX);
786 if(mvpUniformInfo && !mvpUniformInfo->name.empty())
788 Matrix modelViewProjectionMatrix(false);
789 MatrixUtils::MultiplyProjectionMatrix(modelViewProjectionMatrix, modelViewMatrix, projectionMatrix);
790 WriteDefaultUniform(mvpUniformInfo, *uboView, modelViewProjectionMatrix);
793 auto normalUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::NORMAL_MATRIX);
794 if(normalUniformInfo && !normalUniformInfo->name.empty())
796 Matrix3 normalMatrix(modelViewMatrix);
797 normalMatrix.Invert();
798 normalMatrix.Transpose();
799 WriteDefaultUniform(normalUniformInfo, *uboView, normalMatrix);
802 Vector4 finalColor; ///< Applied renderer's opacity color
803 const Vector4& color = node.GetRenderColor(bufferIndex); ///< Actor's original color
804 if(mPremultipliedAlphaEnabled)
806 const float& alpha = color.a * mRenderDataProvider->GetOpacity(bufferIndex);
807 finalColor = Vector4(color.r * alpha, color.g * alpha, color.b * alpha, alpha);
811 finalColor = Vector4(color.r, color.g, color.b, color.a * mRenderDataProvider->GetOpacity(bufferIndex));
813 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::COLOR), *uboView, finalColor);
814 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::ACTOR_COLOR), *uboView, color);
816 // Write uniforms from the uniform map
817 FillUniformBuffer(*program, instruction, *uboView, bindings, uboOffset, bufferIndex, nodeIndex);
819 // Write uSize in the end, as it shouldn't be overridable by dynamic properties.
820 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::SIZE), *uboView, size);
822 commandBuffer.BindUniformBuffers(*bindings);
827 bool Renderer::WriteDefaultUniform(const Graphics::UniformInfo* uniformInfo, Render::UniformBufferView& ubo, const T& data)
829 if(uniformInfo && !uniformInfo->name.empty())
831 WriteUniform(ubo, *uniformInfo, data);
838 void Renderer::WriteUniform(Render::UniformBufferView& ubo, const Graphics::UniformInfo& uniformInfo, const T& data)
840 WriteUniform(ubo, uniformInfo, &data, sizeof(T));
843 void Renderer::WriteUniform(Render::UniformBufferView& ubo, const Graphics::UniformInfo& uniformInfo, const void* data, uint32_t size)
845 ubo.Write(data, size, ubo.GetOffset() + uniformInfo.offset);
848 void Renderer::FillUniformBuffer(Program& program,
849 const SceneGraph::RenderInstruction& instruction,
850 Render::UniformBufferView& ubo,
851 std::vector<Graphics::UniformBufferBinding>*& outBindings,
853 BufferIndex updateBufferIndex,
854 std::size_t nodeIndex)
856 auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
857 auto uboCount = reflection.GetUniformBlockCount();
860 uint32_t dataOffset = offset;
861 for(auto i = 0u; i < uboCount; ++i)
863 mUniformBufferBindings[i].dataSize = reflection.GetUniformBlockSize(i);
864 mUniformBufferBindings[i].binding = reflection.GetUniformBlockBinding(i);
866 dataOffset += GetUniformBufferDataAlignment(mUniformBufferBindings[i].dataSize);
867 mUniformBufferBindings[i].buffer = ubo.GetBuffer(&mUniformBufferBindings[i].offset);
869 for(auto iter = mUniformIndexMaps[nodeIndex].begin(),
870 end = mUniformIndexMaps[nodeIndex].end();
874 auto& uniform = *iter;
875 int arrayIndex = uniform.arrayIndex;
877 if(!uniform.uniformFunc)
879 auto uniformInfo = Graphics::UniformInfo{};
880 auto uniformFound = program.GetUniform(uniform.uniformName.GetStringView(),
881 uniform.uniformNameHash,
882 uniform.uniformNameHashNoArray,
885 uniform.uniformOffset = uniformInfo.offset;
886 uniform.uniformLocation = uniformInfo.location;
890 auto dst = ubo.GetOffset() + uniformInfo.offset;
891 const auto typeSize = GetPropertyValueSizeForUniform((*iter).propertyValue->GetType());
892 const auto dest = dst + static_cast<uint32_t>(typeSize) * arrayIndex;
893 const auto func = GetPropertyValueGetter((*iter).propertyValue->GetType());
895 ubo.Write(&((*iter).propertyValue->*func)(updateBufferIndex),
899 uniform.uniformSize = typeSize;
900 uniform.uniformFunc = func;
905 auto dst = ubo.GetOffset() + uniform.uniformOffset;
906 const auto typeSize = uniform.uniformSize;
907 const auto dest = dst + static_cast<uint32_t>(typeSize) * arrayIndex;
908 const auto func = uniform.uniformFunc;
910 ubo.Write(&((*iter).propertyValue->*func)(updateBufferIndex),
916 // write output bindings
917 outBindings = &mUniformBufferBindings;
923 void Renderer::SetSortAttributes(SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const
925 sortAttributes.shader = &(mRenderDataProvider->GetShader());
926 sortAttributes.geometry = mGeometry;
929 void Renderer::SetShaderChanged(bool value)
931 mShaderChanged = value;
934 bool Renderer::Updated(BufferIndex bufferIndex)
936 if(mRenderCallback || mShaderChanged || mGeometry->AttributesChanged() || mRenderDataProvider->IsUpdated())
941 auto* textures = mRenderDataProvider->GetTextures();
944 for(auto iter = textures->Begin(), end = textures->End(); iter < end; ++iter)
946 auto texture = *iter;
947 if(texture && texture->Updated())
956 Vector4 Renderer::GetVisualTransformedUpdateArea(BufferIndex bufferIndex, const Vector4& originalUpdateArea) const noexcept
958 return mRenderDataProvider->GetVisualTransformedUpdateArea(bufferIndex, originalUpdateArea);
961 Graphics::Pipeline& Renderer::PrepareGraphicsPipeline(
963 const Dali::Internal::SceneGraph::RenderInstruction& instruction,
964 const SceneGraph::NodeDataProvider& node,
967 // Prepare query info
968 PipelineCacheQueryInfo queryInfo{};
969 queryInfo.program = &program;
970 queryInfo.renderer = this;
971 queryInfo.geometry = mGeometry;
972 queryInfo.blendingEnabled = blend;
973 queryInfo.blendingOptions = &mBlendingOptions;
974 queryInfo.alphaPremultiplied = mPremultipliedAlphaEnabled;
975 queryInfo.cameraUsingReflection = instruction.GetCamera()->GetReflectionUsed();
977 queryInfo.GenerateHash();
979 // Reset old pipeline
980 if(DALI_LIKELY(mPipelineCached))
982 mPipelineCache->ResetPipeline(mPipeline);
983 mPipelineCached = false;
986 // Find or generate new pipeline.
987 auto pipelineResult = mPipelineCache->GetPipeline(queryInfo, true);
989 mPipeline = pipelineResult.level2;
990 mPipelineCached = true;
992 // should be never null?
993 return *pipelineResult.pipeline;
996 void Renderer::SetRenderCallback(RenderCallback* callback)
998 mRenderCallback = callback;
1001 } // namespace Render
1003 } // namespace Dali::Internal