2 * Copyright (c) 2021 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-program.h>
23 #include <dali/graphics-api/graphics-types.h>
24 #include <dali/integration-api/debug.h>
25 #include <dali/internal/common/image-sampler.h>
26 #include <dali/internal/render/common/render-instruction.h>
27 #include <dali/internal/render/data-providers/node-data-provider.h>
28 #include <dali/internal/render/data-providers/uniform-map-data-provider.h>
29 #include <dali/internal/render/renderers/render-sampler.h>
30 #include <dali/internal/render/renderers/render-texture.h>
31 #include <dali/internal/render/renderers/render-vertex-buffer.h>
32 #include <dali/internal/render/renderers/shader-cache.h>
33 #include <dali/internal/render/shaders/program.h>
34 #include <dali/internal/render/shaders/render-shader.h>
35 #include <dali/internal/update/common/uniform-map.h>
43 // Size of uniform buffer page used when resizing
44 constexpr uint32_t UBO_PAGE_SIZE = 8192u;
46 // UBO allocation threshold below which the UBO will shrink
47 constexpr auto UBO_SHRINK_THRESHOLD = 0.75f;
49 // Helper to get the vertex input format
50 Dali::Graphics::VertexInputFormat GetPropertyVertexFormat(Property::Type propertyType)
52 Dali::Graphics::VertexInputFormat type{};
57 case Property::STRING:
60 case Property::EXTENTS: // i4?
61 case Property::RECTANGLE: // i4/f4?
62 case Property::ROTATION:
64 type = Dali::Graphics::VertexInputFormat::UNDEFINED;
67 case Property::BOOLEAN:
69 type = Dali::Graphics::VertexInputFormat::UNDEFINED; // type = GL_BYTE; @todo new type for this?
72 case Property::INTEGER:
74 type = Dali::Graphics::VertexInputFormat::INTEGER; // (short)
79 type = Dali::Graphics::VertexInputFormat::FLOAT;
82 case Property::VECTOR2:
84 type = Dali::Graphics::VertexInputFormat::FVECTOR2;
87 case Property::VECTOR3:
89 type = Dali::Graphics::VertexInputFormat::FVECTOR3;
92 case Property::VECTOR4:
94 type = Dali::Graphics::VertexInputFormat::FVECTOR4;
97 case Property::MATRIX3:
99 type = Dali::Graphics::VertexInputFormat::FLOAT;
102 case Property::MATRIX:
104 type = Dali::Graphics::VertexInputFormat::FLOAT;
112 constexpr Graphics::CullMode ConvertCullFace(Dali::FaceCullingMode::Type mode)
116 case Dali::FaceCullingMode::NONE:
118 return Graphics::CullMode::NONE;
120 case Dali::FaceCullingMode::FRONT:
122 return Graphics::CullMode::FRONT;
124 case Dali::FaceCullingMode::BACK:
126 return Graphics::CullMode::BACK;
128 case Dali::FaceCullingMode::FRONT_AND_BACK:
130 return Graphics::CullMode::FRONT_AND_BACK;
133 return Graphics::CullMode::NONE;
136 constexpr Graphics::BlendFactor ConvertBlendFactor(BlendFactor::Type blendFactor)
140 case BlendFactor::ZERO:
141 return Graphics::BlendFactor::ZERO;
142 case BlendFactor::ONE:
143 return Graphics::BlendFactor::ONE;
144 case BlendFactor::SRC_COLOR:
145 return Graphics::BlendFactor::SRC_COLOR;
146 case BlendFactor::ONE_MINUS_SRC_COLOR:
147 return Graphics::BlendFactor::ONE_MINUS_SRC_COLOR;
148 case BlendFactor::SRC_ALPHA:
149 return Graphics::BlendFactor::SRC_ALPHA;
150 case BlendFactor::ONE_MINUS_SRC_ALPHA:
151 return Graphics::BlendFactor::ONE_MINUS_SRC_ALPHA;
152 case BlendFactor::DST_ALPHA:
153 return Graphics::BlendFactor::DST_ALPHA;
154 case BlendFactor::ONE_MINUS_DST_ALPHA:
155 return Graphics::BlendFactor::ONE_MINUS_DST_ALPHA;
156 case BlendFactor::DST_COLOR:
157 return Graphics::BlendFactor::DST_COLOR;
158 case BlendFactor::ONE_MINUS_DST_COLOR:
159 return Graphics::BlendFactor::ONE_MINUS_DST_COLOR;
160 case BlendFactor::SRC_ALPHA_SATURATE:
161 return Graphics::BlendFactor::SRC_ALPHA_SATURATE;
162 case BlendFactor::CONSTANT_COLOR:
163 return Graphics::BlendFactor::CONSTANT_COLOR;
164 case BlendFactor::ONE_MINUS_CONSTANT_COLOR:
165 return Graphics::BlendFactor::ONE_MINUS_CONSTANT_COLOR;
166 case BlendFactor::CONSTANT_ALPHA:
167 return Graphics::BlendFactor::CONSTANT_ALPHA;
168 case BlendFactor::ONE_MINUS_CONSTANT_ALPHA:
169 return Graphics::BlendFactor::ONE_MINUS_CONSTANT_ALPHA;
171 return Graphics::BlendFactor{};
174 constexpr Graphics::BlendOp ConvertBlendEquation(DevelBlendEquation::Type blendEquation)
176 switch(blendEquation)
178 case DevelBlendEquation::ADD:
179 return Graphics::BlendOp::ADD;
180 case DevelBlendEquation::SUBTRACT:
181 return Graphics::BlendOp::SUBTRACT;
182 case DevelBlendEquation::REVERSE_SUBTRACT:
183 return Graphics::BlendOp::REVERSE_SUBTRACT;
184 case DevelBlendEquation::COLOR:
185 case DevelBlendEquation::COLOR_BURN:
186 case DevelBlendEquation::COLOR_DODGE:
187 case DevelBlendEquation::DARKEN:
188 case DevelBlendEquation::DIFFERENCE:
189 case DevelBlendEquation::EXCLUSION:
190 case DevelBlendEquation::HARD_LIGHT:
191 case DevelBlendEquation::HUE:
192 case DevelBlendEquation::LIGHTEN:
193 case DevelBlendEquation::LUMINOSITY:
194 case DevelBlendEquation::MAX:
195 case DevelBlendEquation::MIN:
196 case DevelBlendEquation::MULTIPLY:
197 case DevelBlendEquation::OVERLAY:
198 case DevelBlendEquation::SATURATION:
199 case DevelBlendEquation::SCREEN:
200 case DevelBlendEquation::SOFT_LIGHT:
201 return Graphics::BlendOp{};
203 return Graphics::BlendOp{};
207 * Helper function to calculate the correct alignment of data for uniform buffers
208 * @param dataSize size of uniform buffer
209 * @return aligned offset of data
211 inline uint32_t GetUniformBufferDataAlignment(uint32_t dataSize)
213 return ((dataSize / 256u) + ((dataSize % 256u) ? 1u : 0u)) * 256u;
220 Renderer* Renderer::New(SceneGraph::RenderDataProvider* dataProvider,
221 Render::Geometry* geometry,
222 uint32_t blendingBitmask,
223 const Vector4& blendColor,
224 FaceCullingMode::Type faceCullingMode,
225 bool preMultipliedAlphaEnabled,
226 DepthWriteMode::Type depthWriteMode,
227 DepthTestMode::Type depthTestMode,
228 DepthFunction::Type depthFunction,
229 StencilParameters& stencilParameters)
231 return new Renderer(dataProvider, geometry, blendingBitmask, blendColor, faceCullingMode, preMultipliedAlphaEnabled, depthWriteMode, depthTestMode, depthFunction, stencilParameters);
234 Renderer::Renderer(SceneGraph::RenderDataProvider* dataProvider,
235 Render::Geometry* geometry,
236 uint32_t blendingBitmask,
237 const Vector4& blendColor,
238 FaceCullingMode::Type faceCullingMode,
239 bool preMultipliedAlphaEnabled,
240 DepthWriteMode::Type depthWriteMode,
241 DepthTestMode::Type depthTestMode,
242 DepthFunction::Type depthFunction,
243 StencilParameters& stencilParameters)
244 : mGraphicsController(nullptr),
245 mRenderDataProvider(dataProvider),
247 mProgramCache(nullptr),
249 mAttributeLocations(),
251 mStencilParameters(stencilParameters),
253 mIndexedDrawFirstElement(0),
254 mIndexedDrawElementsCount(0),
255 mDepthFunction(depthFunction),
256 mFaceCullingMode(faceCullingMode),
257 mDepthWriteMode(depthWriteMode),
258 mDepthTestMode(depthTestMode),
259 mUpdateAttributeLocations(true),
260 mPremultipledAlphaEnabled(preMultipliedAlphaEnabled),
261 mShaderChanged(false),
264 if(blendingBitmask != 0u)
266 mBlendingOptions.SetBitmask(blendingBitmask);
269 mBlendingOptions.SetBlendColor(blendColor);
272 void Renderer::Initialize(Graphics::Controller& graphicsController, ProgramCache& programCache, Render::ShaderCache& shaderCache, Render::UniformBufferManager& uniformBufferManager)
274 mGraphicsController = &graphicsController;
275 mProgramCache = &programCache;
276 mShaderCache = &shaderCache;
277 mUniformBufferManager = &uniformBufferManager;
280 Renderer::~Renderer() = default;
282 void Renderer::SetGeometry(Render::Geometry* geometry)
284 mGeometry = geometry;
285 mUpdateAttributeLocations = true;
287 void Renderer::SetDrawCommands(Dali::DevelRenderer::DrawCommand* pDrawCommands, uint32_t size)
289 mDrawCommands.clear();
290 mDrawCommands.insert(mDrawCommands.end(), pDrawCommands, pDrawCommands + size);
293 void Renderer::BindTextures(Graphics::CommandBuffer& commandBuffer, Vector<Graphics::Texture*>& boundTextures)
295 uint32_t textureUnit = 0;
297 std::vector<Render::Sampler*>& samplers(mRenderDataProvider->GetSamplers());
298 std::vector<Render::Texture*>& textures(mRenderDataProvider->GetTextures());
300 std::vector<Graphics::TextureBinding> textureBindings;
301 for(uint32_t i = 0; i < static_cast<uint32_t>(textures.size()); ++i) // not expecting more than uint32_t of textures
303 if(textures[i] && textures[i]->GetGraphicsObject())
305 // if the sampler exists,
306 // if it's default, delete the graphics object
307 // otherwise re-initialize it if dirty
309 const Graphics::Sampler* graphicsSampler = (samplers[i] ? samplers[i]->GetGraphicsObject()
312 boundTextures.PushBack(textures[i]->GetGraphicsObject());
313 const Graphics::TextureBinding textureBinding{textures[i]->GetGraphicsObject(), graphicsSampler, textureUnit};
314 textureBindings.push_back(textureBinding);
320 if(textureBindings.size() > 0)
322 commandBuffer.BindTextures(textureBindings);
326 void Renderer::SetFaceCullingMode(FaceCullingMode::Type mode)
328 mFaceCullingMode = mode;
332 void Renderer::SetBlendingBitMask(uint32_t bitmask)
334 mBlendingOptions.SetBitmask(bitmask);
338 void Renderer::SetBlendColor(const Vector4& color)
340 mBlendingOptions.SetBlendColor(color);
344 void Renderer::SetIndexedDrawFirstElement(uint32_t firstElement)
346 mIndexedDrawFirstElement = firstElement;
350 void Renderer::SetIndexedDrawElementsCount(uint32_t elementsCount)
352 mIndexedDrawElementsCount = elementsCount;
356 void Renderer::EnablePreMultipliedAlpha(bool enable)
358 mPremultipledAlphaEnabled = enable;
362 void Renderer::SetDepthWriteMode(DepthWriteMode::Type depthWriteMode)
364 mDepthWriteMode = depthWriteMode;
368 void Renderer::SetDepthTestMode(DepthTestMode::Type depthTestMode)
370 mDepthTestMode = depthTestMode;
374 DepthWriteMode::Type Renderer::GetDepthWriteMode() const
376 return mDepthWriteMode;
379 DepthTestMode::Type Renderer::GetDepthTestMode() const
381 return mDepthTestMode;
384 void Renderer::SetDepthFunction(DepthFunction::Type depthFunction)
386 mDepthFunction = depthFunction;
390 DepthFunction::Type Renderer::GetDepthFunction() const
392 return mDepthFunction;
395 void Renderer::SetRenderMode(RenderMode::Type renderMode)
397 mStencilParameters.renderMode = renderMode;
401 RenderMode::Type Renderer::GetRenderMode() const
403 return mStencilParameters.renderMode;
406 void Renderer::SetStencilFunction(StencilFunction::Type stencilFunction)
408 mStencilParameters.stencilFunction = stencilFunction;
412 StencilFunction::Type Renderer::GetStencilFunction() const
414 return mStencilParameters.stencilFunction;
417 void Renderer::SetStencilFunctionMask(int stencilFunctionMask)
419 mStencilParameters.stencilFunctionMask = stencilFunctionMask;
423 int Renderer::GetStencilFunctionMask() const
425 return mStencilParameters.stencilFunctionMask;
428 void Renderer::SetStencilFunctionReference(int stencilFunctionReference)
430 mStencilParameters.stencilFunctionReference = stencilFunctionReference;
434 int Renderer::GetStencilFunctionReference() const
436 return mStencilParameters.stencilFunctionReference;
439 void Renderer::SetStencilMask(int stencilMask)
441 mStencilParameters.stencilMask = stencilMask;
445 int Renderer::GetStencilMask() const
447 return mStencilParameters.stencilMask;
450 void Renderer::SetStencilOperationOnFail(StencilOperation::Type stencilOperationOnFail)
452 mStencilParameters.stencilOperationOnFail = stencilOperationOnFail;
456 StencilOperation::Type Renderer::GetStencilOperationOnFail() const
458 return mStencilParameters.stencilOperationOnFail;
461 void Renderer::SetStencilOperationOnZFail(StencilOperation::Type stencilOperationOnZFail)
463 mStencilParameters.stencilOperationOnZFail = stencilOperationOnZFail;
467 StencilOperation::Type Renderer::GetStencilOperationOnZFail() const
469 return mStencilParameters.stencilOperationOnZFail;
472 void Renderer::SetStencilOperationOnZPass(StencilOperation::Type stencilOperationOnZPass)
474 mStencilParameters.stencilOperationOnZPass = stencilOperationOnZPass;
478 StencilOperation::Type Renderer::GetStencilOperationOnZPass() const
480 return mStencilParameters.stencilOperationOnZPass;
483 void Renderer::Upload()
485 mGeometry->Upload(*mGraphicsController);
488 bool Renderer::Render(Graphics::CommandBuffer& commandBuffer,
489 BufferIndex bufferIndex,
490 const SceneGraph::NodeDataProvider& node,
491 const Matrix& modelMatrix,
492 const Matrix& modelViewMatrix,
493 const Matrix& viewMatrix,
494 const Matrix& projectionMatrix,
497 Vector<Graphics::Texture*>& boundTextures,
498 const Dali::Internal::SceneGraph::RenderInstruction& instruction,
501 // Before doing anything test if the call happens in the right queue
502 if(mDrawCommands.empty() && queueIndex > 0)
508 std::vector<DevelRenderer::DrawCommand*> commands;
509 for(auto& cmd : mDrawCommands)
511 if(cmd.queue == queueIndex)
513 commands.emplace_back(&cmd);
517 // Have commands but nothing to be drawn - abort
518 if(!mDrawCommands.empty() && commands.empty())
524 if(!mDrawCommands.empty())
526 blend = (commands[0]->queue == DevelRenderer::RENDER_QUEUE_OPAQUE ? false : blend);
530 ShaderDataPtr shaderData = mRenderDataProvider->GetShader().GetShaderData();
531 const std::vector<char>& vertShader = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::VERTEX_SHADER);
532 const std::vector<char>& fragShader = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER);
533 Dali::Graphics::Shader& vertexShader = mShaderCache->GetShader(
535 Graphics::PipelineStage::VERTEX_SHADER,
536 shaderData->GetSourceMode());
538 Dali::Graphics::Shader& fragmentShader = mShaderCache->GetShader(
540 Graphics::PipelineStage::FRAGMENT_SHADER,
541 shaderData->GetSourceMode());
543 std::vector<Graphics::ShaderState> shaderStates{
544 Graphics::ShaderState()
545 .SetShader(vertexShader)
546 .SetPipelineStage(Graphics::PipelineStage::VERTEX_SHADER),
547 Graphics::ShaderState()
548 .SetShader(fragmentShader)
549 .SetPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER)};
551 auto createInfo = Graphics::ProgramCreateInfo();
552 createInfo.SetShaderState(shaderStates);
554 auto graphicsProgram = mGraphicsController->CreateProgram(createInfo, nullptr);
555 Program* program = Program::New(*mProgramCache,
557 *mGraphicsController,
558 std::move(graphicsProgram));
562 DALI_LOG_ERROR("Failed to get program for shader at address %p.\n", reinterpret_cast<void*>(&mRenderDataProvider->GetShader()));
566 // Prepare the graphics pipeline. This may either re-use an existing pipeline or create a new one.
567 auto& pipeline = PrepareGraphicsPipeline(*program, instruction, node, blend);
569 commandBuffer.BindPipeline(pipeline);
571 BindTextures(commandBuffer, boundTextures);
573 BuildUniformIndexMap(bufferIndex, node, size, *program);
575 WriteUniformBuffer(bufferIndex, commandBuffer, program, instruction, node, modelMatrix, modelViewMatrix, viewMatrix, projectionMatrix, size);
577 bool drawn = false; // Draw can fail if there are no vertex buffers or they haven't been uploaded yet
578 // @todo We should detect this case much earlier to prevent unnecessary work
580 if(mDrawCommands.empty())
582 drawn = mGeometry->Draw(*mGraphicsController, commandBuffer, mIndexedDrawFirstElement, mIndexedDrawElementsCount);
586 for(auto& cmd : commands)
588 mGeometry->Draw(*mGraphicsController, commandBuffer, cmd->firstIndex, cmd->elementCount);
596 void Renderer::BuildUniformIndexMap(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program)
598 // Check if the map has changed
599 DALI_ASSERT_DEBUG(mRenderDataProvider && "No Uniform map data provider available");
601 const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMap();
603 if(uniformMapDataProvider.GetUniformMapChanged(bufferIndex) ||
604 node.GetUniformMapChanged(bufferIndex) ||
605 mUniformIndexMap.Count() == 0 ||
608 // Reset shader pointer
609 mShaderChanged = false;
611 const SceneGraph::CollectedUniformMap& uniformMap = uniformMapDataProvider.GetUniformMap(bufferIndex);
612 const SceneGraph::CollectedUniformMap& uniformMapNode = node.GetUniformMap(bufferIndex);
614 auto maxMaps = static_cast<uint32_t>(uniformMap.Count() + uniformMapNode.Count()); // 4,294,967,295 maps should be enough
615 mUniformIndexMap.Clear(); // Clear contents, but keep memory if we don't change size
616 mUniformIndexMap.Resize(maxMaps);
618 // Copy uniform map into mUniformIndexMap
619 uint32_t mapIndex = 0;
620 for(; mapIndex < uniformMap.Count(); ++mapIndex)
622 mUniformIndexMap[mapIndex].propertyValue = uniformMap[mapIndex].propertyPtr;
623 mUniformIndexMap[mapIndex].uniformName = uniformMap[mapIndex].uniformName;
624 mUniformIndexMap[mapIndex].uniformNameHash = uniformMap[mapIndex].uniformNameHash;
625 mUniformIndexMap[mapIndex].uniformNameHashNoArray = uniformMap[mapIndex].uniformNameHashNoArray;
626 mUniformIndexMap[mapIndex].arrayIndex = uniformMap[mapIndex].arrayIndex;
629 for(uint32_t nodeMapIndex = 0; nodeMapIndex < uniformMapNode.Count(); ++nodeMapIndex)
631 auto hash = uniformMapNode[nodeMapIndex].uniformNameHash;
632 auto& name = uniformMapNode[nodeMapIndex].uniformName;
634 for(uint32_t i = 0; i < uniformMap.Count(); ++i)
636 if(mUniformIndexMap[i].uniformNameHash == hash &&
637 mUniformIndexMap[i].uniformName == name)
639 mUniformIndexMap[i].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
647 mUniformIndexMap[mapIndex].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
648 mUniformIndexMap[mapIndex].uniformName = uniformMapNode[nodeMapIndex].uniformName;
649 mUniformIndexMap[mapIndex].uniformNameHash = uniformMapNode[nodeMapIndex].uniformNameHash;
650 mUniformIndexMap[mapIndex].uniformNameHashNoArray = uniformMapNode[nodeMapIndex].uniformNameHashNoArray;
651 mUniformIndexMap[mapIndex].arrayIndex = uniformMapNode[nodeMapIndex].arrayIndex;
656 mUniformIndexMap.Resize(mapIndex);
660 void Renderer::WriteUniformBuffer(
661 BufferIndex bufferIndex,
662 Graphics::CommandBuffer& commandBuffer,
664 const SceneGraph::RenderInstruction& instruction,
665 const SceneGraph::NodeDataProvider& node,
666 const Matrix& modelMatrix,
667 const Matrix& modelViewMatrix,
668 const Matrix& viewMatrix,
669 const Matrix& projectionMatrix,
673 uint32_t uniformBlockAllocationBytes{0u};
674 uint32_t uniformBlockMaxSize{0u};
675 uint32_t uboOffset{0u};
677 auto& reflection = mGraphicsController->GetProgramReflection(program->GetGraphicsProgram());
678 for(auto i = 0u; i < reflection.GetUniformBlockCount(); ++i)
680 auto blockSize = GetUniformBufferDataAlignment(reflection.GetUniformBlockSize(i));
681 if(uniformBlockMaxSize < blockSize)
683 uniformBlockMaxSize = blockSize;
685 uniformBlockAllocationBytes += blockSize;
688 auto pagedAllocation = ((uniformBlockAllocationBytes / UBO_PAGE_SIZE + 1u)) * UBO_PAGE_SIZE;
690 // Allocate twice memory as required by the uniform buffers
691 // todo: memory usage backlog to use optimal allocation
692 if(uniformBlockAllocationBytes && !mUniformBuffer[bufferIndex])
694 mUniformBuffer[bufferIndex] = mUniformBufferManager->AllocateUniformBuffer(pagedAllocation);
696 else if(uniformBlockAllocationBytes && (mUniformBuffer[bufferIndex]->GetSize() < pagedAllocation ||
697 (pagedAllocation < uint32_t(float(mUniformBuffer[bufferIndex]->GetSize()) * UBO_SHRINK_THRESHOLD))))
699 mUniformBuffer[bufferIndex]->Reserve(pagedAllocation);
703 if(mUniformBuffer[bufferIndex])
705 mUniformBuffer[bufferIndex]->Fill(0, 0u, 0u);
708 // update the uniform buffer
709 // pass shared UBO and offset, return new offset for next item to be used
710 // don't process bindings if there are no uniform buffers allocated
711 auto ubo = mUniformBuffer[bufferIndex].get();
714 auto uboCount = reflection.GetUniformBlockCount();
715 mUniformBufferBindings.resize(uboCount);
717 std::vector<Graphics::UniformBufferBinding>* bindings{&mUniformBufferBindings};
719 // Write default uniforms
720 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_MATRIX), *ubo, *bindings, modelMatrix);
721 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::VIEW_MATRIX), *ubo, *bindings, viewMatrix);
722 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::PROJECTION_MATRIX), *ubo, *bindings, projectionMatrix);
723 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_VIEW_MATRIX), *ubo, *bindings, modelViewMatrix);
725 auto mvpUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::MVP_MATRIX);
726 if(mvpUniformInfo && !mvpUniformInfo->name.empty())
728 Matrix modelViewProjectionMatrix(false);
729 Matrix::Multiply(modelViewProjectionMatrix, modelViewMatrix, projectionMatrix);
730 WriteDefaultUniform(mvpUniformInfo, *ubo, *bindings, modelViewProjectionMatrix);
733 auto normalUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::NORMAL_MATRIX);
734 if(normalUniformInfo && !normalUniformInfo->name.empty())
736 Matrix3 normalMatrix(modelViewMatrix);
737 normalMatrix.Invert();
738 normalMatrix.Transpose();
739 WriteDefaultUniform(normalUniformInfo, *ubo, *bindings, normalMatrix);
743 const Vector4& color = node.GetRenderColor(bufferIndex);
744 if(mPremultipledAlphaEnabled)
746 float alpha = color.a * mRenderDataProvider->GetOpacity(bufferIndex);
747 finalColor = Vector4(color.r * alpha, color.g * alpha, color.b * alpha, alpha);
751 finalColor = Vector4(color.r, color.g, color.b, color.a * mRenderDataProvider->GetOpacity(bufferIndex));
753 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::COLOR), *ubo, *bindings, finalColor);
755 // Write uniforms from the uniform map
756 FillUniformBuffer(*program, instruction, *ubo, bindings, uboOffset, bufferIndex);
758 // Write uSize in the end, as it shouldn't be overridable by dynamic properties.
759 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::SIZE), *ubo, *bindings, size);
761 commandBuffer.BindUniformBuffers(*bindings);
766 bool Renderer::WriteDefaultUniform(const Graphics::UniformInfo* uniformInfo, Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const T& data)
768 if(uniformInfo && !uniformInfo->name.empty())
770 WriteUniform(ubo, bindings, *uniformInfo, data);
777 void Renderer::WriteUniform(Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const Graphics::UniformInfo& uniformInfo, const T& data)
779 WriteUniform(ubo, bindings, uniformInfo, &data, sizeof(T));
782 void Renderer::WriteUniform(Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const Graphics::UniformInfo& uniformInfo, const void* data, uint32_t size)
784 ubo.Write(data, size, bindings[uniformInfo.bufferIndex].offset + uniformInfo.offset);
787 void Renderer::FillUniformBuffer(Program& program,
788 const SceneGraph::RenderInstruction& instruction,
789 Render::UniformBuffer& ubo,
790 std::vector<Graphics::UniformBufferBinding>*& outBindings,
792 BufferIndex updateBufferIndex)
794 auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
795 auto uboCount = reflection.GetUniformBlockCount();
798 uint32_t dataOffset = offset;
799 for(auto i = 0u; i < uboCount; ++i)
801 mUniformBufferBindings[i].dataSize = reflection.GetUniformBlockSize(i);
802 mUniformBufferBindings[i].binding = reflection.GetUniformBlockBinding(i);
803 mUniformBufferBindings[i].offset = dataOffset;
805 dataOffset += GetUniformBufferDataAlignment(mUniformBufferBindings[i].dataSize);
806 mUniformBufferBindings[i].buffer = ubo.GetBuffer();
808 for(UniformIndexMappings::Iterator iter = mUniformIndexMap.Begin(),
809 end = mUniformIndexMap.End();
813 // @todo This means parsing the uniform string every frame. Instead, store the array index if present.
814 int arrayIndex = (*iter).arrayIndex;
816 auto uniformInfo = Graphics::UniformInfo{};
817 auto uniformFound = program.GetUniform((*iter).uniformName.GetCString(),
818 (*iter).uniformNameHashNoArray ? (*iter).uniformNameHashNoArray
819 : (*iter).uniformNameHash,
824 auto dst = mUniformBufferBindings[uniformInfo.bufferIndex].offset + uniformInfo.offset;
826 switch((*iter).propertyValue->GetType())
828 case Property::Type::BOOLEAN:
830 ubo.Write(&(*iter).propertyValue->GetBoolean(updateBufferIndex),
832 dst + static_cast<uint32_t>(sizeof(bool)) * arrayIndex);
835 case Property::Type::INTEGER:
837 ubo.Write(&(*iter).propertyValue->GetInteger(updateBufferIndex),
839 dst + static_cast<int32_t>(sizeof(int32_t)) * arrayIndex);
842 case Property::Type::FLOAT:
844 ubo.Write(&(*iter).propertyValue->GetFloat(updateBufferIndex),
846 dst + static_cast<uint32_t>(sizeof(float)) * arrayIndex);
849 case Property::Type::VECTOR2:
851 ubo.Write(&(*iter).propertyValue->GetVector2(updateBufferIndex),
853 dst + static_cast<uint32_t>(sizeof(Vector2)) * arrayIndex);
856 case Property::Type::VECTOR3:
858 ubo.Write(&(*iter).propertyValue->GetVector3(updateBufferIndex),
860 dst + static_cast<uint32_t>(sizeof(Vector3)) * arrayIndex);
863 case Property::Type::VECTOR4:
865 ubo.Write(&(*iter).propertyValue->GetVector4(updateBufferIndex),
867 dst + static_cast<uint32_t>(sizeof(Vector4)) * arrayIndex);
870 case Property::Type::MATRIX:
872 ubo.Write(&(*iter).propertyValue->GetMatrix(updateBufferIndex),
874 dst + static_cast<uint32_t>(sizeof(Matrix)) * arrayIndex);
877 case Property::Type::MATRIX3:
879 // todo: handle data padding properly
882 //const auto& matrix = &(*iter).propertyValue->GetMatrix3(updateBufferIndex);
883 //for(int i = 0; i < 3; ++i)
885 //ubo.Write(&matrix->AsFloat()[i * 3],
886 // sizeof(float) * 3,
887 // dst + (i * static_cast<uint32_t>(sizeof(Vector4))));
890 ubo.Write(&(*iter).propertyValue->GetMatrix3(updateBufferIndex),
892 dst + static_cast<uint32_t>(sizeof(Matrix3)) * arrayIndex);
902 // write output bindings
903 outBindings = &mUniformBufferBindings;
909 void Renderer::SetSortAttributes(BufferIndex bufferIndex,
910 SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const
912 sortAttributes.shader = &(mRenderDataProvider->GetShader());
913 sortAttributes.geometry = mGeometry;
916 void Renderer::SetShaderChanged(bool value)
918 mShaderChanged = value;
921 bool Renderer::Updated(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider* node)
929 if(mShaderChanged || mUpdateAttributeLocations || mGeometry->AttributesChanged())
934 for(const auto& texture : mRenderDataProvider->GetTextures())
936 if(texture && texture->IsNativeImage())
942 uint64_t hash = 0xc70f6907UL;
943 const SceneGraph::CollectedUniformMap& uniformMapNode = node->GetUniformMap(bufferIndex);
944 for(const auto& uniformProperty : uniformMapNode)
946 hash = uniformProperty.propertyPtr->Hash(bufferIndex, hash);
949 const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMap();
950 const SceneGraph::CollectedUniformMap& uniformMap = uniformMapDataProvider.GetUniformMap(bufferIndex);
951 for(const auto& uniformProperty : uniformMap)
953 hash = uniformProperty.propertyPtr->Hash(bufferIndex, hash);
956 if(mUniformsHash != hash)
958 mUniformsHash = hash;
965 Graphics::Pipeline& Renderer::PrepareGraphicsPipeline(
967 const Dali::Internal::SceneGraph::RenderInstruction& instruction,
968 const SceneGraph::NodeDataProvider& node,
971 Graphics::InputAssemblyState inputAssemblyState{};
972 Graphics::VertexInputState vertexInputState{};
973 Graphics::ProgramState programState{};
974 uint32_t bindingIndex{0u};
976 if(mUpdateAttributeLocations || mGeometry->AttributesChanged())
978 mAttributeLocations.Clear();
979 mUpdateAttributeLocations = true;
982 auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
988 for(auto&& vertexBuffer : mGeometry->GetVertexBuffers())
990 const VertexBuffer::Format& vertexFormat = *vertexBuffer->GetFormat();
992 vertexInputState.bufferBindings.emplace_back(vertexFormat.size, // stride
993 Graphics::VertexInputRate::PER_VERTEX);
995 const uint32_t attributeCount = vertexBuffer->GetAttributeCount();
996 for(uint32_t i = 0; i < attributeCount; ++i)
998 if(mUpdateAttributeLocations)
1000 auto attributeName = vertexBuffer->GetAttributeName(i);
1001 int32_t pLocation = reflection.GetVertexAttributeLocation(std::string(attributeName.GetStringView()));
1004 DALI_LOG_WARNING("Attribute not found in the shader: %s\n", attributeName.GetCString());
1006 mAttributeLocations.PushBack(pLocation);
1009 uint32_t location = static_cast<uint32_t>(mAttributeLocations[base + i]);
1011 vertexInputState.attributes.emplace_back(location,
1013 vertexFormat.components[i].offset,
1014 GetPropertyVertexFormat(vertexFormat.components[i].type));
1016 base += attributeCount;
1019 mUpdateAttributeLocations = false;
1022 inputAssemblyState.SetTopology(mGeometry->GetTopology());
1025 programState.SetProgram(program.GetGraphicsProgram());
1027 Graphics::RasterizationState rasterizationState{};
1029 //Set cull face mode
1030 const Dali::Internal::SceneGraph::Camera* cam = instruction.GetCamera();
1031 if(cam->GetReflectionUsed())
1033 auto adjFaceCullingMode = mFaceCullingMode;
1034 switch(mFaceCullingMode)
1036 case FaceCullingMode::Type::FRONT:
1038 adjFaceCullingMode = FaceCullingMode::Type::BACK;
1041 case FaceCullingMode::Type::BACK:
1043 adjFaceCullingMode = FaceCullingMode::Type::FRONT;
1048 // nothing to do, leave culling as it is
1051 rasterizationState.SetCullMode(ConvertCullFace(adjFaceCullingMode));
1055 rasterizationState.SetCullMode(ConvertCullFace(mFaceCullingMode));
1058 rasterizationState.SetFrontFace(Graphics::FrontFace::COUNTER_CLOCKWISE);
1063 switch(mGeometry->GetTopology())
1065 case Graphics::PrimitiveTopology::TRIANGLE_LIST:
1066 case Graphics::PrimitiveTopology::TRIANGLE_STRIP:
1067 case Graphics::PrimitiveTopology::TRIANGLE_FAN:
1068 rasterizationState.SetPolygonMode(Graphics::PolygonMode::FILL);
1070 case Graphics::PrimitiveTopology::LINE_LIST:
1071 case Graphics::PrimitiveTopology::LINE_LOOP:
1072 case Graphics::PrimitiveTopology::LINE_STRIP:
1073 rasterizationState.SetPolygonMode(Graphics::PolygonMode::LINE);
1075 case Graphics::PrimitiveTopology::POINT_LIST:
1076 rasterizationState.SetPolygonMode(Graphics::PolygonMode::POINT);
1080 // @todo Add blend barrier to the Graphics API if we are using advanced
1081 // blending options. Command?
1083 Graphics::ColorBlendState colorBlendState{};
1084 colorBlendState.SetBlendEnable(false);
1088 colorBlendState.SetBlendEnable(true);
1090 Graphics::BlendOp rgbOp = ConvertBlendEquation(mBlendingOptions.GetBlendEquationRgb());
1091 Graphics::BlendOp alphaOp = ConvertBlendEquation(mBlendingOptions.GetBlendEquationRgb());
1092 if(mBlendingOptions.IsAdvancedBlendEquationApplied() && mPremultipledAlphaEnabled)
1094 if(rgbOp != alphaOp)
1096 DALI_LOG_ERROR("Advanced Blend Equation MUST be applied by using BlendEquation.\n");
1102 .SetSrcColorBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendSrcFactorRgb()))
1103 .SetSrcAlphaBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendSrcFactorAlpha()))
1104 .SetDstColorBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendDestFactorRgb()))
1105 .SetDstAlphaBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendDestFactorAlpha()))
1106 .SetColorBlendOp(rgbOp)
1107 .SetAlphaBlendOp(alphaOp);
1109 // Blend color is optional and rarely used
1110 Vector4* blendColor = const_cast<Vector4*>(mBlendingOptions.GetBlendColor());
1113 colorBlendState.SetBlendConstants(blendColor->AsFloat());
1119 // Create the pipeline
1120 Graphics::PipelineCreateInfo createInfo;
1122 .SetInputAssemblyState(&inputAssemblyState)
1123 .SetVertexInputState(&vertexInputState)
1124 .SetRasterizationState(&rasterizationState)
1125 .SetColorBlendState(&colorBlendState)
1126 .SetProgramState(&programState)
1127 .SetNextExtension(&mLegacyProgram);
1129 // Store a pipeline per renderer per render (renderer can be owned by multiple nodes,
1130 // and re-drawn in multiple instructions).
1131 // @todo This is only needed because ColorBlend state can change. Fixme!
1132 // This is ameliorated by the fact that implementation caches pipelines, and we're only storing
1134 auto hash = HashedPipeline::GetHash(&node, &instruction, blend);
1135 HashedPipeline* hashedPipeline = nullptr;
1136 for(auto& element : mGraphicsPipelines)
1138 if(element.mHash == hash)
1140 hashedPipeline = &element;
1145 if(hashedPipeline != nullptr)
1147 hashedPipeline->mGraphicsPipeline = mGraphicsController->CreatePipeline(
1149 std::move(hashedPipeline->mGraphicsPipeline));
1153 mGraphicsPipelines.emplace_back();
1154 mGraphicsPipelines.back().mHash = hash;
1155 mGraphicsPipelines.back().mGraphicsPipeline = mGraphicsController->CreatePipeline(createInfo, nullptr);
1156 hashedPipeline = &mGraphicsPipelines.back();
1158 return *hashedPipeline->mGraphicsPipeline.get();
1161 } // namespace Render
1163 } // namespace Internal