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/gl-resources/context.h>
30 #include <dali/internal/render/renderers/render-sampler.h>
31 #include <dali/internal/render/renderers/render-texture.h>
32 #include <dali/internal/render/renderers/render-vertex-buffer.h>
33 #include <dali/internal/render/renderers/shader-cache.h>
34 #include <dali/internal/render/shaders/program.h>
35 #include <dali/internal/render/shaders/scene-graph-shader.h>
36 #include <dali/internal/update/common/uniform-map.h>
44 // Size of uniform buffer page used when resizing
45 constexpr uint32_t UBO_PAGE_SIZE = 8192u;
47 // UBO allocation threshold below which the UBO will shrink
48 constexpr auto UBO_SHRINK_THRESHOLD = 0.75f;
50 // Helper to get the vertex input format
51 Dali::Graphics::VertexInputFormat GetPropertyVertexFormat(Property::Type propertyType)
53 Dali::Graphics::VertexInputFormat type{};
58 case Property::STRING:
61 case Property::EXTENTS: // i4?
62 case Property::RECTANGLE: // i4/f4?
63 case Property::ROTATION:
65 type = Dali::Graphics::VertexInputFormat::UNDEFINED;
68 case Property::BOOLEAN:
70 type = Dali::Graphics::VertexInputFormat::UNDEFINED; // type = GL_BYTE; @todo new type for this?
73 case Property::INTEGER:
75 type = Dali::Graphics::VertexInputFormat::INTEGER; // (short)
80 type = Dali::Graphics::VertexInputFormat::FLOAT;
83 case Property::VECTOR2:
85 type = Dali::Graphics::VertexInputFormat::FVECTOR2;
88 case Property::VECTOR3:
90 type = Dali::Graphics::VertexInputFormat::FVECTOR3;
93 case Property::VECTOR4:
95 type = Dali::Graphics::VertexInputFormat::FVECTOR4;
98 case Property::MATRIX3:
100 type = Dali::Graphics::VertexInputFormat::FLOAT;
103 case Property::MATRIX:
105 type = Dali::Graphics::VertexInputFormat::FLOAT;
113 constexpr Graphics::CullMode ConvertCullFace(Dali::FaceCullingMode::Type mode)
117 case Dali::FaceCullingMode::NONE:
119 return Graphics::CullMode::NONE;
121 case Dali::FaceCullingMode::FRONT:
123 return Graphics::CullMode::FRONT;
125 case Dali::FaceCullingMode::BACK:
127 return Graphics::CullMode::BACK;
129 case Dali::FaceCullingMode::FRONT_AND_BACK:
131 return Graphics::CullMode::FRONT_AND_BACK;
134 return Graphics::CullMode::NONE;
137 constexpr Graphics::BlendFactor ConvertBlendFactor(BlendFactor::Type blendFactor)
141 case BlendFactor::ZERO:
142 return Graphics::BlendFactor::ZERO;
143 case BlendFactor::ONE:
144 return Graphics::BlendFactor::ONE;
145 case BlendFactor::SRC_COLOR:
146 return Graphics::BlendFactor::SRC_COLOR;
147 case BlendFactor::ONE_MINUS_SRC_COLOR:
148 return Graphics::BlendFactor::ONE_MINUS_SRC_COLOR;
149 case BlendFactor::SRC_ALPHA:
150 return Graphics::BlendFactor::SRC_ALPHA;
151 case BlendFactor::ONE_MINUS_SRC_ALPHA:
152 return Graphics::BlendFactor::ONE_MINUS_SRC_ALPHA;
153 case BlendFactor::DST_ALPHA:
154 return Graphics::BlendFactor::DST_ALPHA;
155 case BlendFactor::ONE_MINUS_DST_ALPHA:
156 return Graphics::BlendFactor::ONE_MINUS_DST_ALPHA;
157 case BlendFactor::DST_COLOR:
158 return Graphics::BlendFactor::DST_COLOR;
159 case BlendFactor::ONE_MINUS_DST_COLOR:
160 return Graphics::BlendFactor::ONE_MINUS_DST_COLOR;
161 case BlendFactor::SRC_ALPHA_SATURATE:
162 return Graphics::BlendFactor::SRC_ALPHA_SATURATE;
163 case BlendFactor::CONSTANT_COLOR:
164 return Graphics::BlendFactor::CONSTANT_COLOR;
165 case BlendFactor::ONE_MINUS_CONSTANT_COLOR:
166 return Graphics::BlendFactor::ONE_MINUS_CONSTANT_COLOR;
167 case BlendFactor::CONSTANT_ALPHA:
168 return Graphics::BlendFactor::CONSTANT_ALPHA;
169 case BlendFactor::ONE_MINUS_CONSTANT_ALPHA:
170 return Graphics::BlendFactor::ONE_MINUS_CONSTANT_ALPHA;
172 return Graphics::BlendFactor{};
175 constexpr Graphics::BlendOp ConvertBlendEquation(DevelBlendEquation::Type blendEquation)
177 switch(blendEquation)
179 case DevelBlendEquation::ADD:
180 return Graphics::BlendOp::ADD;
181 case DevelBlendEquation::SUBTRACT:
182 return Graphics::BlendOp::SUBTRACT;
183 case DevelBlendEquation::REVERSE_SUBTRACT:
184 return Graphics::BlendOp::REVERSE_SUBTRACT;
185 case DevelBlendEquation::COLOR:
186 case DevelBlendEquation::COLOR_BURN:
187 case DevelBlendEquation::COLOR_DODGE:
188 case DevelBlendEquation::DARKEN:
189 case DevelBlendEquation::DIFFERENCE:
190 case DevelBlendEquation::EXCLUSION:
191 case DevelBlendEquation::HARD_LIGHT:
192 case DevelBlendEquation::HUE:
193 case DevelBlendEquation::LIGHTEN:
194 case DevelBlendEquation::LUMINOSITY:
195 case DevelBlendEquation::MAX:
196 case DevelBlendEquation::MIN:
197 case DevelBlendEquation::MULTIPLY:
198 case DevelBlendEquation::OVERLAY:
199 case DevelBlendEquation::SATURATION:
200 case DevelBlendEquation::SCREEN:
201 case DevelBlendEquation::SOFT_LIGHT:
202 return Graphics::BlendOp{};
204 return Graphics::BlendOp{};
208 * Helper function to calculate the correct alignment of data for uniform buffers
209 * @param dataSize size of uniform buffer
210 * @return aligned offset of data
212 inline uint32_t GetUniformBufferDataAlignment(uint32_t dataSize)
214 return ((dataSize / 256u) + ((dataSize % 256u) ? 1u : 0u)) * 256u;
221 Renderer* Renderer::New(SceneGraph::RenderDataProvider* dataProvider,
222 Render::Geometry* geometry,
223 uint32_t blendingBitmask,
224 const Vector4& blendColor,
225 FaceCullingMode::Type faceCullingMode,
226 bool preMultipliedAlphaEnabled,
227 DepthWriteMode::Type depthWriteMode,
228 DepthTestMode::Type depthTestMode,
229 DepthFunction::Type depthFunction,
230 StencilParameters& stencilParameters)
232 return new Renderer(dataProvider, geometry, blendingBitmask, blendColor, faceCullingMode, preMultipliedAlphaEnabled, depthWriteMode, depthTestMode, depthFunction, stencilParameters);
235 Renderer::Renderer(SceneGraph::RenderDataProvider* dataProvider,
236 Render::Geometry* geometry,
237 uint32_t blendingBitmask,
238 const Vector4& blendColor,
239 FaceCullingMode::Type faceCullingMode,
240 bool preMultipliedAlphaEnabled,
241 DepthWriteMode::Type depthWriteMode,
242 DepthTestMode::Type depthTestMode,
243 DepthFunction::Type depthFunction,
244 StencilParameters& stencilParameters)
245 : mGraphicsController(nullptr),
246 mRenderDataProvider(dataProvider),
249 mProgramCache(nullptr),
251 mAttributeLocations(),
253 mStencilParameters(stencilParameters),
255 mIndexedDrawFirstElement(0),
256 mIndexedDrawElementsCount(0),
257 mDepthFunction(depthFunction),
258 mFaceCullingMode(faceCullingMode),
259 mDepthWriteMode(depthWriteMode),
260 mDepthTestMode(depthTestMode),
261 mUpdateAttributeLocations(true),
262 mPremultipledAlphaEnabled(preMultipliedAlphaEnabled),
263 mShaderChanged(false),
266 if(blendingBitmask != 0u)
268 mBlendingOptions.SetBitmask(blendingBitmask);
271 mBlendingOptions.SetBlendColor(blendColor);
274 void Renderer::Initialize(Context& context, Graphics::Controller& graphicsController, ProgramCache& programCache, Render::ShaderCache& shaderCache, Render::UniformBufferManager& uniformBufferManager)
277 mGraphicsController = &graphicsController;
278 mProgramCache = &programCache;
279 mShaderCache = &shaderCache;
280 mUniformBufferManager = &uniformBufferManager;
283 Renderer::~Renderer() = default;
285 void Renderer::SetGeometry(Render::Geometry* geometry)
287 mGeometry = geometry;
288 mUpdateAttributeLocations = true;
290 void Renderer::SetDrawCommands(Dali::DevelRenderer::DrawCommand* pDrawCommands, uint32_t size)
292 mDrawCommands.clear();
293 mDrawCommands.insert(mDrawCommands.end(), pDrawCommands, pDrawCommands + size);
296 void Renderer::GlContextDestroyed()
298 mGeometry->GlContextDestroyed();
301 void Renderer::GlCleanup()
305 void Renderer::SetUniformFromProperty(BufferIndex bufferIndex, Program& program, UniformIndexMap& map)
307 GLint location = program.GetUniformLocation(map.uniformIndex);
308 if(Program::UNIFORM_UNKNOWN != location)
310 // switch based on property type to use correct GL uniform setter
311 switch(map.propertyValue->GetType())
313 case Property::INTEGER:
315 program.SetUniform1i(location, map.propertyValue->GetInteger(bufferIndex));
318 case Property::FLOAT:
320 program.SetUniform1f(location, map.propertyValue->GetFloat(bufferIndex));
323 case Property::VECTOR2:
325 Vector2 value(map.propertyValue->GetVector2(bufferIndex));
326 program.SetUniform2f(location, value.x, value.y);
330 case Property::VECTOR3:
332 Vector3 value(map.propertyValue->GetVector3(bufferIndex));
333 program.SetUniform3f(location, value.x, value.y, value.z);
337 case Property::VECTOR4:
339 Vector4 value(map.propertyValue->GetVector4(bufferIndex));
340 program.SetUniform4f(location, value.x, value.y, value.z, value.w);
344 case Property::ROTATION:
346 Quaternion value(map.propertyValue->GetQuaternion(bufferIndex));
347 program.SetUniform4f(location, value.mVector.x, value.mVector.y, value.mVector.z, value.mVector.w);
351 case Property::MATRIX:
353 const Matrix& value = map.propertyValue->GetMatrix(bufferIndex);
354 program.SetUniformMatrix4fv(location, 1, value.AsFloat());
358 case Property::MATRIX3:
360 const Matrix3& value = map.propertyValue->GetMatrix3(bufferIndex);
361 program.SetUniformMatrix3fv(location, 1, value.AsFloat());
367 // Other property types are ignored
374 void Renderer::BindTextures(Program& program, Graphics::CommandBuffer& commandBuffer, Vector<Graphics::Texture*>& boundTextures)
376 uint32_t textureUnit = 0;
378 GLint uniformLocation(-1);
379 std::vector<Render::Sampler*>& samplers(mRenderDataProvider->GetSamplers());
380 std::vector<Render::Texture*>& textures(mRenderDataProvider->GetTextures());
382 std::vector<Graphics::TextureBinding> textureBindings;
383 for(uint32_t i = 0; i < static_cast<uint32_t>(textures.size()); ++i) // not expecting more than uint32_t of textures
385 if(textures[i] && textures[i]->GetGraphicsObject())
387 if(program.GetSamplerUniformLocation(i, uniformLocation))
389 // if the sampler exists,
390 // if it's default, delete the graphics object
391 // otherwise re-initialize it if dirty
393 const Graphics::Sampler* graphicsSampler = (samplers[i] ? samplers[i]->GetGraphicsObject()
396 boundTextures.PushBack(textures[i]->GetGraphicsObject());
397 const Graphics::TextureBinding textureBinding{textures[i]->GetGraphicsObject(), graphicsSampler, textureUnit};
398 textureBindings.push_back(textureBinding);
400 program.SetUniform1i(uniformLocation, textureUnit); // Get through shader reflection
406 if(textureBindings.size() > 0)
408 commandBuffer.BindTextures(textureBindings);
412 void Renderer::SetFaceCullingMode(FaceCullingMode::Type mode)
414 mFaceCullingMode = mode;
418 void Renderer::SetBlendingBitMask(uint32_t bitmask)
420 mBlendingOptions.SetBitmask(bitmask);
424 void Renderer::SetBlendColor(const Vector4& color)
426 mBlendingOptions.SetBlendColor(color);
430 void Renderer::SetIndexedDrawFirstElement(uint32_t firstElement)
432 mIndexedDrawFirstElement = firstElement;
436 void Renderer::SetIndexedDrawElementsCount(uint32_t elementsCount)
438 mIndexedDrawElementsCount = elementsCount;
442 void Renderer::EnablePreMultipliedAlpha(bool enable)
444 mPremultipledAlphaEnabled = enable;
448 void Renderer::SetDepthWriteMode(DepthWriteMode::Type depthWriteMode)
450 mDepthWriteMode = depthWriteMode;
454 void Renderer::SetDepthTestMode(DepthTestMode::Type depthTestMode)
456 mDepthTestMode = depthTestMode;
460 DepthWriteMode::Type Renderer::GetDepthWriteMode() const
462 return mDepthWriteMode;
465 DepthTestMode::Type Renderer::GetDepthTestMode() const
467 return mDepthTestMode;
470 void Renderer::SetDepthFunction(DepthFunction::Type depthFunction)
472 mDepthFunction = depthFunction;
476 DepthFunction::Type Renderer::GetDepthFunction() const
478 return mDepthFunction;
481 void Renderer::SetRenderMode(RenderMode::Type renderMode)
483 mStencilParameters.renderMode = renderMode;
487 RenderMode::Type Renderer::GetRenderMode() const
489 return mStencilParameters.renderMode;
492 void Renderer::SetStencilFunction(StencilFunction::Type stencilFunction)
494 mStencilParameters.stencilFunction = stencilFunction;
498 StencilFunction::Type Renderer::GetStencilFunction() const
500 return mStencilParameters.stencilFunction;
503 void Renderer::SetStencilFunctionMask(int stencilFunctionMask)
505 mStencilParameters.stencilFunctionMask = stencilFunctionMask;
509 int Renderer::GetStencilFunctionMask() const
511 return mStencilParameters.stencilFunctionMask;
514 void Renderer::SetStencilFunctionReference(int stencilFunctionReference)
516 mStencilParameters.stencilFunctionReference = stencilFunctionReference;
520 int Renderer::GetStencilFunctionReference() const
522 return mStencilParameters.stencilFunctionReference;
525 void Renderer::SetStencilMask(int stencilMask)
527 mStencilParameters.stencilMask = stencilMask;
531 int Renderer::GetStencilMask() const
533 return mStencilParameters.stencilMask;
536 void Renderer::SetStencilOperationOnFail(StencilOperation::Type stencilOperationOnFail)
538 mStencilParameters.stencilOperationOnFail = stencilOperationOnFail;
542 StencilOperation::Type Renderer::GetStencilOperationOnFail() const
544 return mStencilParameters.stencilOperationOnFail;
547 void Renderer::SetStencilOperationOnZFail(StencilOperation::Type stencilOperationOnZFail)
549 mStencilParameters.stencilOperationOnZFail = stencilOperationOnZFail;
553 StencilOperation::Type Renderer::GetStencilOperationOnZFail() const
555 return mStencilParameters.stencilOperationOnZFail;
558 void Renderer::SetStencilOperationOnZPass(StencilOperation::Type stencilOperationOnZPass)
560 mStencilParameters.stencilOperationOnZPass = stencilOperationOnZPass;
564 StencilOperation::Type Renderer::GetStencilOperationOnZPass() const
566 return mStencilParameters.stencilOperationOnZPass;
569 void Renderer::Upload()
571 mGeometry->Upload(*mGraphicsController);
574 bool Renderer::Render(Context& context,
575 BufferIndex bufferIndex,
576 const SceneGraph::NodeDataProvider& node,
577 const Matrix& modelMatrix,
578 const Matrix& modelViewMatrix,
579 const Matrix& viewMatrix,
580 const Matrix& projectionMatrix,
583 Vector<Graphics::Texture*>& boundTextures,
584 const Dali::Internal::SceneGraph::RenderInstruction& instruction,
587 // Before doing anything test if the call happens in the right queue
588 if(mDrawCommands.empty() && queueIndex > 0)
594 std::vector<DevelRenderer::DrawCommand*> commands;
595 for(auto& cmd : mDrawCommands)
597 if(cmd.queue == queueIndex)
599 commands.emplace_back(&cmd);
603 // Have commands but nothing to be drawn - abort
604 if(!mDrawCommands.empty() && commands.empty())
609 // Create command buffer if not present
610 if(!mGraphicsCommandBuffer)
612 mGraphicsCommandBuffer = mGraphicsController->CreateCommandBuffer(
613 Graphics::CommandBufferCreateInfo()
614 .SetLevel(Graphics::CommandBufferLevel::SECONDARY),
619 mGraphicsCommandBuffer->Reset();
622 auto& commandBuffer = mGraphicsCommandBuffer;
625 if(!mDrawCommands.empty())
627 blend = (commands[0]->queue == DevelRenderer::RENDER_QUEUE_OPAQUE ? false : blend);
631 ShaderDataPtr shaderData = mRenderDataProvider->GetShader().GetShaderData();
632 const std::vector<char>& vertShader = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::VERTEX_SHADER);
633 const std::vector<char>& fragShader = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER);
634 Dali::Graphics::Shader& vertexShader = mShaderCache->GetShader(
636 Graphics::PipelineStage::VERTEX_SHADER,
637 shaderData->GetSourceMode());
639 Dali::Graphics::Shader& fragmentShader = mShaderCache->GetShader(
641 Graphics::PipelineStage::FRAGMENT_SHADER,
642 shaderData->GetSourceMode());
644 std::vector<Graphics::ShaderState> shaderStates{
645 Graphics::ShaderState()
646 .SetShader(vertexShader)
647 .SetPipelineStage(Graphics::PipelineStage::VERTEX_SHADER),
648 Graphics::ShaderState()
649 .SetShader(fragmentShader)
650 .SetPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER)};
652 auto createInfo = Graphics::ProgramCreateInfo();
653 createInfo.SetShaderState(shaderStates);
655 auto graphicsProgram = mGraphicsController->CreateProgram(createInfo, nullptr);
656 Program* program = Program::New(*mProgramCache,
658 *mGraphicsController,
659 std::move(graphicsProgram),
660 (shaderData->GetHints() & Dali::Shader::Hint::MODIFIES_GEOMETRY) != 0x0);
664 DALI_LOG_ERROR("Failed to get program for shader at address %p.\n", reinterpret_cast<void*>(&mRenderDataProvider->GetShader()));
668 // Temporarily create a pipeline here - this will be used for transporting
669 // topology, vertex format, attrs, rasterization state
670 mGraphicsPipeline = PrepareGraphicsPipeline(*program, instruction, blend, std::move(mGraphicsPipeline));
672 commandBuffer->BindPipeline(*mGraphicsPipeline.get());
674 BindTextures(*program, *commandBuffer.get(), boundTextures);
676 BuildUniformIndexMap(bufferIndex, node, size, *program);
678 WriteUniformBuffer(bufferIndex, *commandBuffer.get(), program, instruction, node, modelMatrix, modelViewMatrix, viewMatrix, projectionMatrix, size);
680 bool drawn = false; // Draw can fail if there are no vertex buffers or they haven't been uploaded yet
681 // @todo We should detect this case much earlier to prevent unnecessary work
683 //@todo manage mDrawCommands in the same way as above command buffer?!
684 if(mDrawCommands.empty())
686 drawn = mGeometry->Draw(*mGraphicsController, *commandBuffer.get(), mIndexedDrawFirstElement, mIndexedDrawElementsCount);
690 for(auto& cmd : commands)
692 // @todo This should generate a command buffer per cmd
693 // Tests WILL fail. (Temporarily commented out)
694 mGeometry->Draw(*mGraphicsController, *commandBuffer.get(), cmd->firstIndex, cmd->elementCount);
698 // Command buffer contains Texture bindings, vertex bindings, index buffer binding, pipeline(vertex format)
699 // @todo We should return the command buffer(s) and let the calling method submit
700 // If not drawn, then don't add command buffer to submit info, and if empty, don't
705 Graphics::SubmitInfo submitInfo{{}, 0 | Graphics::SubmitFlagBits::FLUSH};
706 submitInfo.cmdBuffer.push_back(commandBuffer.get());
707 mGraphicsController->SubmitCommandBuffers(submitInfo);
714 void Renderer::BuildUniformIndexMap(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program)
716 // Check if the map has changed
717 DALI_ASSERT_DEBUG(mRenderDataProvider && "No Uniform map data provider available");
719 const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMap();
721 if(uniformMapDataProvider.GetUniformMapChanged(bufferIndex) ||
722 node.GetUniformMapChanged(bufferIndex) ||
723 mUniformIndexMap.Count() == 0 ||
726 // Reset shader pointer
727 mShaderChanged = false;
729 const SceneGraph::CollectedUniformMap& uniformMap = uniformMapDataProvider.GetUniformMap(bufferIndex);
730 const SceneGraph::CollectedUniformMap& uniformMapNode = node.GetUniformMap(bufferIndex);
732 uint32_t maxMaps = static_cast<uint32_t>(uniformMap.Count() + uniformMapNode.Count()); // 4,294,967,295 maps should be enough
733 mUniformIndexMap.Clear(); // Clear contents, but keep memory if we don't change size
734 mUniformIndexMap.Resize(maxMaps);
736 uint32_t mapIndex = 0;
737 for(; mapIndex < uniformMap.Count(); ++mapIndex)
739 mUniformIndexMap[mapIndex].propertyValue = uniformMap[mapIndex].propertyPtr;
740 mUniformIndexMap[mapIndex].uniformIndex = program.RegisterUniform(uniformMap[mapIndex].uniformName);
741 mUniformIndexMap[mapIndex].uniformName = uniformMap[mapIndex].uniformName;
742 mUniformIndexMap[mapIndex].uniformNameHash = uniformMap[mapIndex].uniformNameHash;
743 mUniformIndexMap[mapIndex].uniformNameHashNoArray = uniformMap[mapIndex].uniformNameHashNoArray;
744 mUniformIndexMap[mapIndex].arrayIndex = uniformMap[mapIndex].arrayIndex;
747 for(uint32_t nodeMapIndex = 0; nodeMapIndex < uniformMapNode.Count(); ++nodeMapIndex)
749 uint32_t uniformIndex = program.RegisterUniform(uniformMapNode[nodeMapIndex].uniformName);
751 for(uint32_t i = 0; i < uniformMap.Count(); ++i)
753 if(mUniformIndexMap[i].uniformIndex == uniformIndex)
755 mUniformIndexMap[i].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
763 mUniformIndexMap[mapIndex].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
764 mUniformIndexMap[mapIndex].uniformName = uniformMapNode[nodeMapIndex].uniformName;
765 mUniformIndexMap[mapIndex].uniformIndex = uniformIndex;
766 mUniformIndexMap[mapIndex].uniformNameHash = uniformMapNode[nodeMapIndex].uniformNameHash;
767 mUniformIndexMap[mapIndex].uniformNameHashNoArray = uniformMapNode[nodeMapIndex].uniformNameHashNoArray;
768 mUniformIndexMap[mapIndex].arrayIndex = uniformMapNode[nodeMapIndex].arrayIndex;
773 mUniformIndexMap.Resize(mapIndex);
777 void Renderer::WriteUniformBuffer(
778 BufferIndex bufferIndex,
779 Graphics::CommandBuffer& commandBuffer,
781 const SceneGraph::RenderInstruction& instruction,
782 const SceneGraph::NodeDataProvider& node,
783 const Matrix& modelMatrix,
784 const Matrix& modelViewMatrix,
785 const Matrix& viewMatrix,
786 const Matrix& projectionMatrix,
790 uint32_t uniformBlockAllocationBytes{0u};
791 uint32_t uniformBlockMaxSize{0u};
792 uint32_t uboOffset{0u};
794 auto& reflection = mGraphicsController->GetProgramReflection(program->GetGraphicsProgram());
795 for(auto i = 0u; i < reflection.GetUniformBlockCount(); ++i)
797 auto blockSize = GetUniformBufferDataAlignment(reflection.GetUniformBlockSize(i));
798 if(uniformBlockMaxSize < blockSize)
800 uniformBlockMaxSize = blockSize;
802 uniformBlockAllocationBytes += blockSize;
805 auto pagedAllocation = ((uniformBlockAllocationBytes / UBO_PAGE_SIZE + 1u)) * UBO_PAGE_SIZE;
807 // Allocate twice memory as required by the uniform buffers
808 // todo: memory usage backlog to use optimal allocation
809 if(uniformBlockAllocationBytes && !mUniformBuffer[bufferIndex])
811 mUniformBuffer[bufferIndex] = mUniformBufferManager->AllocateUniformBuffer(pagedAllocation);
813 else if(uniformBlockAllocationBytes && (mUniformBuffer[bufferIndex]->GetSize() < pagedAllocation ||
814 (pagedAllocation < uint32_t(float(mUniformBuffer[bufferIndex]->GetSize()) * UBO_SHRINK_THRESHOLD))))
816 mUniformBuffer[bufferIndex]->Reserve(pagedAllocation);
820 if(mUniformBuffer[bufferIndex])
822 mUniformBuffer[bufferIndex]->Fill(0, 0u, 0u);
825 // update the uniform buffer
826 // pass shared UBO and offset, return new offset for next item to be used
827 // don't process bindings if there are no uniform buffers allocated
828 auto ubo = mUniformBuffer[bufferIndex].get();
831 auto uboCount = reflection.GetUniformBlockCount();
832 mUniformBufferBindings.resize(uboCount);
834 std::vector<Graphics::UniformBufferBinding>* bindings{&mUniformBufferBindings};
836 // Write default uniforms
837 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_MATRIX), *ubo, *bindings, modelMatrix);
838 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::VIEW_MATRIX), *ubo, *bindings, viewMatrix);
839 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::PROJECTION_MATRIX), *ubo, *bindings, projectionMatrix);
840 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_VIEW_MATRIX), *ubo, *bindings, modelViewMatrix);
842 auto mvpUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::MVP_MATRIX);
843 if(mvpUniformInfo && !mvpUniformInfo->name.empty())
845 Matrix modelViewProjectionMatrix(false);
846 Matrix::Multiply(modelViewProjectionMatrix, modelViewMatrix, projectionMatrix);
847 WriteDefaultUniform(mvpUniformInfo, *ubo, *bindings, modelViewProjectionMatrix);
850 auto normalUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::NORMAL_MATRIX);
851 if(normalUniformInfo && !normalUniformInfo->name.empty())
853 Matrix3 normalMatrix(modelViewMatrix);
854 normalMatrix.Invert();
855 normalMatrix.Transpose();
856 WriteDefaultUniform(normalUniformInfo, *ubo, *bindings, normalMatrix);
860 const Vector4& color = node.GetRenderColor(bufferIndex);
861 if(mPremultipledAlphaEnabled)
863 float alpha = color.a * mRenderDataProvider->GetOpacity(bufferIndex);
864 finalColor = Vector4(color.r * alpha, color.g * alpha, color.b * alpha, alpha);
868 finalColor = Vector4(color.r, color.g, color.b, color.a * mRenderDataProvider->GetOpacity(bufferIndex));
870 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::COLOR), *ubo, *bindings, finalColor);
872 // Write uniforms from the uniform map
873 FillUniformBuffer(*program, instruction, *ubo, bindings, uboOffset, bufferIndex);
875 // Write uSize in the end, as it shouldn't be overridable by dynamic properties.
876 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::SIZE), *ubo, *bindings, size);
878 commandBuffer.BindUniformBuffers(*bindings);
883 bool Renderer::WriteDefaultUniform(const Graphics::UniformInfo* uniformInfo, Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const T& data)
885 if(uniformInfo && !uniformInfo->name.empty())
887 WriteUniform(ubo, bindings, *uniformInfo, data);
894 void Renderer::WriteUniform(Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const Graphics::UniformInfo& uniformInfo, const T& data)
896 WriteUniform(ubo, bindings, uniformInfo, &data, sizeof(T));
899 void Renderer::WriteUniform(Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const Graphics::UniformInfo& uniformInfo, const void* data, uint32_t size)
901 ubo.Write(data, size, bindings[uniformInfo.bufferIndex].offset + uniformInfo.offset);
904 void Renderer::FillUniformBuffer(Program& program,
905 const SceneGraph::RenderInstruction& instruction,
906 Render::UniformBuffer& ubo,
907 std::vector<Graphics::UniformBufferBinding>*& outBindings,
909 BufferIndex updateBufferIndex)
911 auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
912 auto uboCount = reflection.GetUniformBlockCount();
915 uint32_t dataOffset = offset;
916 for(auto i = 0u; i < uboCount; ++i)
918 mUniformBufferBindings[i].dataSize = reflection.GetUniformBlockSize(i);
919 mUniformBufferBindings[i].binding = reflection.GetUniformBlockBinding(i);
920 mUniformBufferBindings[i].offset = dataOffset;
922 dataOffset += GetUniformBufferDataAlignment(mUniformBufferBindings[i].dataSize);
923 mUniformBufferBindings[i].buffer = ubo.GetBuffer();
925 for(UniformIndexMappings::Iterator iter = mUniformIndexMap.Begin(),
926 end = mUniformIndexMap.End();
930 // @todo This means parsing the uniform string every frame. Instead, store the array index if present.
931 int arrayIndex = (*iter).arrayIndex;
933 auto uniformInfo = Graphics::UniformInfo{};
934 auto uniformFound = program.GetUniform((*iter).uniformName.GetCString(),
935 (*iter).uniformNameHashNoArray ? (*iter).uniformNameHashNoArray
936 : (*iter).uniformNameHash,
941 auto dst = mUniformBufferBindings[uniformInfo.bufferIndex].offset + uniformInfo.offset;
943 switch((*iter).propertyValue->GetType())
945 case Property::Type::BOOLEAN:
947 ubo.Write(&(*iter).propertyValue->GetBoolean(updateBufferIndex),
949 dst + static_cast<uint32_t>(sizeof(bool)) * arrayIndex);
952 case Property::Type::INTEGER:
954 ubo.Write(&(*iter).propertyValue->GetInteger(updateBufferIndex),
956 dst + static_cast<int32_t>(sizeof(int32_t)) * arrayIndex);
959 case Property::Type::FLOAT:
961 ubo.Write(&(*iter).propertyValue->GetFloat(updateBufferIndex),
963 dst + static_cast<uint32_t>(sizeof(float)) * arrayIndex);
966 case Property::Type::VECTOR2:
968 ubo.Write(&(*iter).propertyValue->GetVector2(updateBufferIndex),
970 dst + static_cast<uint32_t>(sizeof(Vector2)) * arrayIndex);
973 case Property::Type::VECTOR3:
975 ubo.Write(&(*iter).propertyValue->GetVector3(updateBufferIndex),
977 dst + static_cast<uint32_t>(sizeof(Vector3)) * arrayIndex);
980 case Property::Type::VECTOR4:
982 ubo.Write(&(*iter).propertyValue->GetVector4(updateBufferIndex),
984 dst + static_cast<uint32_t>(sizeof(Vector4)) * arrayIndex);
987 case Property::Type::MATRIX:
989 ubo.Write(&(*iter).propertyValue->GetMatrix(updateBufferIndex),
991 dst + static_cast<uint32_t>(sizeof(Matrix)) * arrayIndex);
994 case Property::Type::MATRIX3:
996 // todo: handle data padding properly
999 //const auto& matrix = &(*iter).propertyValue->GetMatrix3(updateBufferIndex);
1000 //for(int i = 0; i < 3; ++i)
1002 //ubo.Write(&matrix->AsFloat()[i * 3],
1003 // sizeof(float) * 3,
1004 // dst + (i * static_cast<uint32_t>(sizeof(Vector4))));
1007 ubo.Write(&(*iter).propertyValue->GetMatrix3(updateBufferIndex),
1009 dst + static_cast<uint32_t>(sizeof(Matrix3)) * arrayIndex);
1019 // write output bindings
1020 outBindings = &mUniformBufferBindings;
1023 offset = dataOffset;
1026 void Renderer::SetSortAttributes(BufferIndex bufferIndex,
1027 SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const
1029 sortAttributes.shader = &(mRenderDataProvider->GetShader());
1030 sortAttributes.geometry = mGeometry;
1033 void Renderer::SetShaderChanged(bool value)
1035 mShaderChanged = value;
1038 bool Renderer::Updated(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider* node)
1046 if(mShaderChanged || mUpdateAttributeLocations || mGeometry->AttributesChanged())
1051 for(const auto& texture : mRenderDataProvider->GetTextures())
1053 if(texture && texture->IsNativeImage())
1059 uint64_t hash = 0xc70f6907UL;
1060 const SceneGraph::CollectedUniformMap& uniformMapNode = node->GetUniformMap(bufferIndex);
1061 for(const auto& uniformProperty : uniformMapNode)
1063 hash = uniformProperty.propertyPtr->Hash(bufferIndex, hash);
1066 const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMap();
1067 const SceneGraph::CollectedUniformMap& uniformMap = uniformMapDataProvider.GetUniformMap(bufferIndex);
1068 for(const auto& uniformProperty : uniformMap)
1070 hash = uniformProperty.propertyPtr->Hash(bufferIndex, hash);
1073 if(mUniformsHash != hash)
1075 mUniformsHash = hash;
1082 Graphics::UniquePtr<Graphics::Pipeline> Renderer::PrepareGraphicsPipeline(
1084 const Dali::Internal::SceneGraph::RenderInstruction& instruction,
1086 Graphics::UniquePtr<Graphics::Pipeline>&& oldPipeline)
1088 Graphics::InputAssemblyState inputAssemblyState{};
1089 Graphics::VertexInputState vertexInputState{};
1090 Graphics::ProgramState programState{};
1091 uint32_t bindingIndex{0u};
1093 if(mUpdateAttributeLocations || mGeometry->AttributesChanged())
1095 mAttributeLocations.Clear();
1096 mUpdateAttributeLocations = true;
1099 auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
1105 for(auto&& vertexBuffer : mGeometry->GetVertexBuffers())
1107 const VertexBuffer::Format& vertexFormat = *vertexBuffer->GetFormat();
1109 vertexInputState.bufferBindings.emplace_back(vertexFormat.size, // stride
1110 Graphics::VertexInputRate::PER_VERTEX);
1112 const uint32_t attributeCount = vertexBuffer->GetAttributeCount();
1113 for(uint32_t i = 0; i < attributeCount; ++i)
1115 if(mUpdateAttributeLocations)
1117 auto attributeName = vertexBuffer->GetAttributeName(i);
1118 int32_t pLocation = reflection.GetVertexAttributeLocation(std::string(attributeName.GetStringView()));
1121 DALI_LOG_WARNING("Attribute not found in the shader: %s\n", attributeName.GetCString());
1123 mAttributeLocations.PushBack(pLocation);
1126 uint32_t location = static_cast<uint32_t>(mAttributeLocations[base + i]);
1128 vertexInputState.attributes.emplace_back(location,
1130 vertexFormat.components[i].offset,
1131 GetPropertyVertexFormat(vertexFormat.components[i].type));
1133 base += attributeCount;
1136 mUpdateAttributeLocations = false;
1139 inputAssemblyState.SetTopology(mGeometry->GetTopology());
1142 programState.SetProgram(program.GetGraphicsProgram());
1144 Graphics::RasterizationState rasterizationState{};
1146 //Set cull face mode
1147 const Dali::Internal::SceneGraph::Camera* cam = instruction.GetCamera();
1148 if(cam->GetReflectionUsed())
1150 auto adjFaceCullingMode = mFaceCullingMode;
1151 switch(mFaceCullingMode)
1153 case FaceCullingMode::Type::FRONT:
1155 adjFaceCullingMode = FaceCullingMode::Type::BACK;
1158 case FaceCullingMode::Type::BACK:
1160 adjFaceCullingMode = FaceCullingMode::Type::FRONT;
1165 // nothing to do, leave culling as it is
1168 rasterizationState.SetCullMode(ConvertCullFace(adjFaceCullingMode));
1172 rasterizationState.SetCullMode(ConvertCullFace(mFaceCullingMode));
1175 rasterizationState.SetFrontFace(Graphics::FrontFace::COUNTER_CLOCKWISE);
1180 switch(mGeometry->GetTopology())
1182 case Graphics::PrimitiveTopology::TRIANGLE_LIST:
1183 case Graphics::PrimitiveTopology::TRIANGLE_STRIP:
1184 case Graphics::PrimitiveTopology::TRIANGLE_FAN:
1185 rasterizationState.SetPolygonMode(Graphics::PolygonMode::FILL);
1187 case Graphics::PrimitiveTopology::LINE_LIST:
1188 case Graphics::PrimitiveTopology::LINE_LOOP:
1189 case Graphics::PrimitiveTopology::LINE_STRIP:
1190 rasterizationState.SetPolygonMode(Graphics::PolygonMode::LINE);
1192 case Graphics::PrimitiveTopology::POINT_LIST:
1193 rasterizationState.SetPolygonMode(Graphics::PolygonMode::POINT);
1197 // @todo How to signal a blend barrier is needed?
1198 //if(mBlendingOptions.IsAdvancedBlendEquationApplied() && mPremultipledAlphaEnabled)
1200 // context.BlendBarrier();
1203 Graphics::ColorBlendState colorBlendState{};
1204 colorBlendState.SetBlendEnable(false);
1208 colorBlendState.SetBlendEnable(true);
1210 Graphics::BlendOp rgbOp = ConvertBlendEquation(mBlendingOptions.GetBlendEquationRgb());
1211 Graphics::BlendOp alphaOp = ConvertBlendEquation(mBlendingOptions.GetBlendEquationRgb());
1212 if(mBlendingOptions.IsAdvancedBlendEquationApplied() && mPremultipledAlphaEnabled)
1214 if(rgbOp != alphaOp)
1216 DALI_LOG_ERROR("Advanced Blend Equation MUST be applied by using BlendEquation.\n");
1222 .SetSrcColorBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendSrcFactorRgb()))
1223 .SetSrcAlphaBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendSrcFactorAlpha()))
1224 .SetDstColorBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendDestFactorRgb()))
1225 .SetDstAlphaBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendDestFactorAlpha()))
1226 .SetColorBlendOp(rgbOp)
1227 .SetAlphaBlendOp(alphaOp);
1229 // Blend color is optional and rarely used
1230 Vector4* blendColor = const_cast<Vector4*>(mBlendingOptions.GetBlendColor());
1233 colorBlendState.SetBlendConstants(blendColor->AsFloat());
1237 // Take the program into use so we can send uniforms to it
1238 // @todo Remove this call entirely!
1243 // Create a new pipeline
1244 // @todo Passed as pointers - shallow copy will break. Implementation MUST deep copy.
1245 return mGraphicsController->CreatePipeline(
1246 Graphics::PipelineCreateInfo()
1247 .SetInputAssemblyState(&inputAssemblyState)
1248 .SetVertexInputState(&vertexInputState)
1249 .SetRasterizationState(&rasterizationState)
1250 .SetColorBlendState(&colorBlendState)
1251 .SetProgramState(&programState)
1252 .SetNextExtension(&mLegacyProgram),
1253 std::move(oldPipeline));
1256 } // namespace Render
1258 } // namespace Internal