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/internal/common/image-sampler.h>
25 #include <dali/internal/render/common/render-instruction.h>
26 #include <dali/internal/render/data-providers/node-data-provider.h>
27 #include <dali/internal/render/data-providers/uniform-map-data-provider.h>
28 #include <dali/internal/render/gl-resources/context.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/scene-graph-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 : 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(Context& context, Graphics::Controller& graphicsController, ProgramCache& programCache, Render::ShaderCache& shaderCache, Render::UniformBufferManager& uniformBufferManager)
275 mGraphicsController = &graphicsController;
276 mProgramCache = &programCache;
277 mShaderCache = &shaderCache;
278 mUniformBufferManager = &uniformBufferManager;
281 Renderer::~Renderer() = default;
283 void Renderer::SetGeometry(Render::Geometry* geometry)
285 mGeometry = geometry;
286 mUpdateAttributeLocations = true;
288 void Renderer::SetDrawCommands(Dali::DevelRenderer::DrawCommand* pDrawCommands, uint32_t size)
290 mDrawCommands.clear();
291 mDrawCommands.insert(mDrawCommands.end(), pDrawCommands, pDrawCommands + size);
294 void Renderer::GlContextDestroyed()
296 mGeometry->GlContextDestroyed();
299 void Renderer::GlCleanup()
303 void Renderer::SetUniformFromProperty(BufferIndex bufferIndex, Program& program, UniformIndexMap& map)
305 GLint location = program.GetUniformLocation(map.uniformIndex);
306 if(Program::UNIFORM_UNKNOWN != location)
308 // switch based on property type to use correct GL uniform setter
309 switch(map.propertyValue->GetType())
311 case Property::INTEGER:
313 program.SetUniform1i(location, map.propertyValue->GetInteger(bufferIndex));
316 case Property::FLOAT:
318 program.SetUniform1f(location, map.propertyValue->GetFloat(bufferIndex));
321 case Property::VECTOR2:
323 Vector2 value(map.propertyValue->GetVector2(bufferIndex));
324 program.SetUniform2f(location, value.x, value.y);
328 case Property::VECTOR3:
330 Vector3 value(map.propertyValue->GetVector3(bufferIndex));
331 program.SetUniform3f(location, value.x, value.y, value.z);
335 case Property::VECTOR4:
337 Vector4 value(map.propertyValue->GetVector4(bufferIndex));
338 program.SetUniform4f(location, value.x, value.y, value.z, value.w);
342 case Property::ROTATION:
344 Quaternion value(map.propertyValue->GetQuaternion(bufferIndex));
345 program.SetUniform4f(location, value.mVector.x, value.mVector.y, value.mVector.z, value.mVector.w);
349 case Property::MATRIX:
351 const Matrix& value = map.propertyValue->GetMatrix(bufferIndex);
352 program.SetUniformMatrix4fv(location, 1, value.AsFloat());
356 case Property::MATRIX3:
358 const Matrix3& value = map.propertyValue->GetMatrix3(bufferIndex);
359 program.SetUniformMatrix3fv(location, 1, value.AsFloat());
365 // Other property types are ignored
372 void Renderer::BindTextures(Program& program, Graphics::CommandBuffer& commandBuffer, Vector<Graphics::Texture*>& boundTextures)
374 uint32_t textureUnit = 0;
376 GLint uniformLocation(-1);
377 std::vector<Render::Sampler*>& samplers(mRenderDataProvider->GetSamplers());
378 std::vector<Render::Texture*>& textures(mRenderDataProvider->GetTextures());
380 std::vector<Graphics::TextureBinding> textureBindings;
381 for(uint32_t i = 0; i < static_cast<uint32_t>(textures.size()); ++i) // not expecting more than uint32_t of textures
383 if(textures[i] && textures[i]->GetGraphicsObject())
385 if(program.GetSamplerUniformLocation(i, uniformLocation))
387 // if the sampler exists,
388 // if it's default, delete the graphics object
389 // otherwise re-initialize it if dirty
391 const Graphics::Sampler* graphicsSampler = (samplers[i] ? samplers[i]->GetGraphicsObject()
394 boundTextures.PushBack(textures[i]->GetGraphicsObject());
395 const Graphics::TextureBinding textureBinding{textures[i]->GetGraphicsObject(), graphicsSampler, textureUnit};
396 textureBindings.push_back(textureBinding);
398 program.SetUniform1i(uniformLocation, textureUnit); // Get through shader reflection
404 if(textureBindings.size() > 0)
406 commandBuffer.BindTextures(textureBindings);
410 void Renderer::SetFaceCullingMode(FaceCullingMode::Type mode)
412 mFaceCullingMode = mode;
416 void Renderer::SetBlendingBitMask(uint32_t bitmask)
418 mBlendingOptions.SetBitmask(bitmask);
422 void Renderer::SetBlendColor(const Vector4& color)
424 mBlendingOptions.SetBlendColor(color);
428 void Renderer::SetIndexedDrawFirstElement(uint32_t firstElement)
430 mIndexedDrawFirstElement = firstElement;
434 void Renderer::SetIndexedDrawElementsCount(uint32_t elementsCount)
436 mIndexedDrawElementsCount = elementsCount;
440 void Renderer::EnablePreMultipliedAlpha(bool enable)
442 mPremultipledAlphaEnabled = enable;
446 void Renderer::SetDepthWriteMode(DepthWriteMode::Type depthWriteMode)
448 mDepthWriteMode = depthWriteMode;
452 void Renderer::SetDepthTestMode(DepthTestMode::Type depthTestMode)
454 mDepthTestMode = depthTestMode;
458 DepthWriteMode::Type Renderer::GetDepthWriteMode() const
460 return mDepthWriteMode;
463 DepthTestMode::Type Renderer::GetDepthTestMode() const
465 return mDepthTestMode;
468 void Renderer::SetDepthFunction(DepthFunction::Type depthFunction)
470 mDepthFunction = depthFunction;
474 DepthFunction::Type Renderer::GetDepthFunction() const
476 return mDepthFunction;
479 void Renderer::SetRenderMode(RenderMode::Type renderMode)
481 mStencilParameters.renderMode = renderMode;
485 RenderMode::Type Renderer::GetRenderMode() const
487 return mStencilParameters.renderMode;
490 void Renderer::SetStencilFunction(StencilFunction::Type stencilFunction)
492 mStencilParameters.stencilFunction = stencilFunction;
496 StencilFunction::Type Renderer::GetStencilFunction() const
498 return mStencilParameters.stencilFunction;
501 void Renderer::SetStencilFunctionMask(int stencilFunctionMask)
503 mStencilParameters.stencilFunctionMask = stencilFunctionMask;
507 int Renderer::GetStencilFunctionMask() const
509 return mStencilParameters.stencilFunctionMask;
512 void Renderer::SetStencilFunctionReference(int stencilFunctionReference)
514 mStencilParameters.stencilFunctionReference = stencilFunctionReference;
518 int Renderer::GetStencilFunctionReference() const
520 return mStencilParameters.stencilFunctionReference;
523 void Renderer::SetStencilMask(int stencilMask)
525 mStencilParameters.stencilMask = stencilMask;
529 int Renderer::GetStencilMask() const
531 return mStencilParameters.stencilMask;
534 void Renderer::SetStencilOperationOnFail(StencilOperation::Type stencilOperationOnFail)
536 mStencilParameters.stencilOperationOnFail = stencilOperationOnFail;
540 StencilOperation::Type Renderer::GetStencilOperationOnFail() const
542 return mStencilParameters.stencilOperationOnFail;
545 void Renderer::SetStencilOperationOnZFail(StencilOperation::Type stencilOperationOnZFail)
547 mStencilParameters.stencilOperationOnZFail = stencilOperationOnZFail;
551 StencilOperation::Type Renderer::GetStencilOperationOnZFail() const
553 return mStencilParameters.stencilOperationOnZFail;
556 void Renderer::SetStencilOperationOnZPass(StencilOperation::Type stencilOperationOnZPass)
558 mStencilParameters.stencilOperationOnZPass = stencilOperationOnZPass;
562 StencilOperation::Type Renderer::GetStencilOperationOnZPass() const
564 return mStencilParameters.stencilOperationOnZPass;
567 void Renderer::Upload()
569 mGeometry->Upload(*mGraphicsController);
572 void Renderer::Render(Context& context,
573 BufferIndex bufferIndex,
574 const SceneGraph::NodeDataProvider& node,
575 const Matrix& modelMatrix,
576 const Matrix& modelViewMatrix,
577 const Matrix& viewMatrix,
578 const Matrix& projectionMatrix,
581 Vector<Graphics::Texture*>& boundTextures,
582 const Dali::Internal::SceneGraph::RenderInstruction& instruction,
585 // Before doing anything test if the call happens in the right queue
586 if(mDrawCommands.empty() && queueIndex > 0)
592 std::vector<DevelRenderer::DrawCommand*> commands;
593 for(auto& cmd : mDrawCommands)
595 if(cmd.queue == queueIndex)
597 commands.emplace_back(&cmd);
601 // Have commands but nothing to be drawn - abort
602 if(!mDrawCommands.empty() && commands.empty())
607 // Create command buffer if not present
608 if(!mGraphicsCommandBuffer)
610 mGraphicsCommandBuffer = mGraphicsController->CreateCommandBuffer(
611 Graphics::CommandBufferCreateInfo()
612 .SetLevel(Graphics::CommandBufferLevel::SECONDARY),
617 mGraphicsCommandBuffer->Reset();
620 auto& commandBuffer = mGraphicsCommandBuffer;
623 if(!mDrawCommands.empty())
625 blend = (commands[0]->queue == DevelRenderer::RENDER_QUEUE_OPAQUE ? false : blend);
629 ShaderDataPtr shaderData = mRenderDataProvider->GetShader().GetShaderData();
630 const std::vector<char>& vertShader = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::VERTEX_SHADER);
631 const std::vector<char>& fragShader = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER);
632 Dali::Graphics::Shader& vertexShader = mShaderCache->GetShader(
634 Graphics::PipelineStage::VERTEX_SHADER,
635 shaderData->GetSourceMode());
637 Dali::Graphics::Shader& fragmentShader = mShaderCache->GetShader(
639 Graphics::PipelineStage::FRAGMENT_SHADER,
640 shaderData->GetSourceMode());
642 std::vector<Graphics::ShaderState> shaderStates{
643 Graphics::ShaderState()
644 .SetShader(vertexShader)
645 .SetPipelineStage(Graphics::PipelineStage::VERTEX_SHADER),
646 Graphics::ShaderState()
647 .SetShader(fragmentShader)
648 .SetPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER)};
650 auto createInfo = Graphics::ProgramCreateInfo();
651 createInfo.SetShaderState(shaderStates);
653 auto graphicsProgram = mGraphicsController->CreateProgram(createInfo, nullptr);
654 Program* program = Program::New(*mProgramCache,
656 *mGraphicsController,
657 std::move(graphicsProgram),
658 (shaderData->GetHints() & Dali::Shader::Hint::MODIFIES_GEOMETRY) != 0x0);
662 DALI_LOG_ERROR("Failed to get program for shader at address %p.\n", reinterpret_cast<void*>(&mRenderDataProvider->GetShader()));
666 // Temporarily create a pipeline here - this will be used for transporting
667 // topology, vertex format, attrs, rasterization state
668 mGraphicsPipeline = PrepareGraphicsPipeline(*program, instruction, blend, std::move(mGraphicsPipeline));
670 commandBuffer->BindPipeline(*mGraphicsPipeline.get());
672 BindTextures(*program, *commandBuffer.get(), boundTextures);
674 BuildUniformIndexMap(bufferIndex, node, size, *program);
676 WriteUniformBuffer(bufferIndex, *commandBuffer.get(), program, instruction, node, modelMatrix, modelViewMatrix, viewMatrix, projectionMatrix, size);
678 bool drawn = false; // Draw can fail if there are no vertex buffers or they haven't been uploaded yet
679 // @todo We should detect this case much earlier to prevent unnecessary work
681 //@todo manage mDrawCommands in the same way as above command buffer?!
682 if(mDrawCommands.empty())
684 drawn = mGeometry->Draw(*mGraphicsController, *commandBuffer.get(), mIndexedDrawFirstElement, mIndexedDrawElementsCount);
688 for(auto& cmd : commands)
690 // @todo This should generate a command buffer per cmd
691 // Tests WILL fail. (Temporarily commented out)
692 mGeometry->Draw(*mGraphicsController, *commandBuffer.get(), cmd->firstIndex, cmd->elementCount);
696 // Command buffer contains Texture bindings, vertex bindings, index buffer binding, pipeline(vertex format)
697 // @todo We should return the command buffer(s) and let the calling method submit
698 // If not drawn, then don't add command buffer to submit info, and if empty, don't
702 Graphics::SubmitInfo submitInfo{{}, 0 | Graphics::SubmitFlagBits::FLUSH};
703 submitInfo.cmdBuffer.push_back(commandBuffer.get());
704 mGraphicsController->SubmitCommandBuffers(submitInfo);
710 void Renderer::BuildUniformIndexMap(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program)
712 // Check if the map has changed
713 DALI_ASSERT_DEBUG(mRenderDataProvider && "No Uniform map data provider available");
715 const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMap();
717 if(uniformMapDataProvider.GetUniformMapChanged(bufferIndex) ||
718 node.GetUniformMapChanged(bufferIndex) ||
719 mUniformIndexMap.Count() == 0 ||
722 // Reset shader pointer
723 mShaderChanged = false;
725 const SceneGraph::CollectedUniformMap& uniformMap = uniformMapDataProvider.GetUniformMap(bufferIndex);
726 const SceneGraph::CollectedUniformMap& uniformMapNode = node.GetUniformMap(bufferIndex);
728 uint32_t maxMaps = static_cast<uint32_t>(uniformMap.Count() + uniformMapNode.Count()); // 4,294,967,295 maps should be enough
729 mUniformIndexMap.Clear(); // Clear contents, but keep memory if we don't change size
730 mUniformIndexMap.Resize(maxMaps);
732 uint32_t mapIndex = 0;
733 for(; mapIndex < uniformMap.Count(); ++mapIndex)
735 mUniformIndexMap[mapIndex].propertyValue = uniformMap[mapIndex].propertyPtr;
736 mUniformIndexMap[mapIndex].uniformIndex = program.RegisterUniform(uniformMap[mapIndex].uniformName);
737 mUniformIndexMap[mapIndex].uniformName = uniformMap[mapIndex].uniformName;
738 mUniformIndexMap[mapIndex].uniformNameHash = uniformMap[mapIndex].uniformNameHash;
739 mUniformIndexMap[mapIndex].uniformNameHashNoArray = uniformMap[mapIndex].uniformNameHashNoArray;
740 mUniformIndexMap[mapIndex].arrayIndex = uniformMap[mapIndex].arrayIndex;
743 for(uint32_t nodeMapIndex = 0; nodeMapIndex < uniformMapNode.Count(); ++nodeMapIndex)
745 uint32_t uniformIndex = program.RegisterUniform(uniformMapNode[nodeMapIndex].uniformName);
747 for(uint32_t i = 0; i < uniformMap.Count(); ++i)
749 if(mUniformIndexMap[i].uniformIndex == uniformIndex)
751 mUniformIndexMap[i].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
759 mUniformIndexMap[mapIndex].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
760 mUniformIndexMap[mapIndex].uniformName = uniformMapNode[nodeMapIndex].uniformName;
761 mUniformIndexMap[mapIndex].uniformIndex = uniformIndex;
762 mUniformIndexMap[mapIndex].uniformNameHash = uniformMapNode[nodeMapIndex].uniformNameHash;
763 mUniformIndexMap[mapIndex].uniformNameHashNoArray = uniformMapNode[nodeMapIndex].uniformNameHashNoArray;
764 mUniformIndexMap[mapIndex].arrayIndex = uniformMapNode[nodeMapIndex].arrayIndex;
769 mUniformIndexMap.Resize(mapIndex);
773 void Renderer::WriteUniformBuffer(
774 BufferIndex bufferIndex,
775 Graphics::CommandBuffer& commandBuffer,
777 const SceneGraph::RenderInstruction& instruction,
778 const SceneGraph::NodeDataProvider& node,
779 const Matrix& modelMatrix,
780 const Matrix& modelViewMatrix,
781 const Matrix& viewMatrix,
782 const Matrix& projectionMatrix,
786 uint32_t uniformBlockAllocationBytes{0u};
787 uint32_t uniformBlockMaxSize{0u};
788 uint32_t uboOffset{0u};
790 auto& reflection = mGraphicsController->GetProgramReflection(program->GetGraphicsProgram());
791 for(auto i = 0u; i < reflection.GetUniformBlockCount(); ++i)
793 auto blockSize = GetUniformBufferDataAlignment(reflection.GetUniformBlockSize(i));
794 if(uniformBlockMaxSize < blockSize)
796 uniformBlockMaxSize = blockSize;
798 uniformBlockAllocationBytes += blockSize;
801 auto pagedAllocation = ((uniformBlockAllocationBytes / UBO_PAGE_SIZE + 1u)) * UBO_PAGE_SIZE;
803 // Allocate twice memory as required by the uniform buffers
804 // todo: memory usage backlog to use optimal allocation
805 if(uniformBlockAllocationBytes && !mUniformBuffer[bufferIndex])
807 mUniformBuffer[bufferIndex] = mUniformBufferManager->AllocateUniformBuffer(pagedAllocation);
809 else if(uniformBlockAllocationBytes && (mUniformBuffer[bufferIndex]->GetSize() < pagedAllocation ||
810 (pagedAllocation < uint32_t(float(mUniformBuffer[bufferIndex]->GetSize()) * UBO_SHRINK_THRESHOLD))))
812 mUniformBuffer[bufferIndex]->Reserve(pagedAllocation);
816 if(mUniformBuffer[bufferIndex])
818 mUniformBuffer[bufferIndex]->Fill(0, 0u, 0u);
821 // update the uniform buffer
822 // pass shared UBO and offset, return new offset for next item to be used
823 // don't process bindings if there are no uniform buffers allocated
824 auto ubo = mUniformBuffer[bufferIndex].get();
827 auto uboCount = reflection.GetUniformBlockCount();
828 mUniformBufferBindings.resize(uboCount);
830 std::vector<Graphics::UniformBufferBinding>* bindings{&mUniformBufferBindings};
832 // Write default uniforms
833 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_MATRIX), *ubo, *bindings, modelMatrix);
834 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::VIEW_MATRIX), *ubo, *bindings, viewMatrix);
835 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::PROJECTION_MATRIX), *ubo, *bindings, projectionMatrix);
836 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_VIEW_MATRIX), *ubo, *bindings, modelViewMatrix);
838 auto mvpUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::MVP_MATRIX);
839 if(mvpUniformInfo && !mvpUniformInfo->name.empty())
841 Matrix modelViewProjectionMatrix(false);
842 Matrix::Multiply(modelViewProjectionMatrix, modelViewMatrix, projectionMatrix);
843 WriteDefaultUniform(mvpUniformInfo, *ubo, *bindings, modelViewProjectionMatrix);
846 auto normalUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::NORMAL_MATRIX);
847 if(normalUniformInfo && !normalUniformInfo->name.empty())
849 Matrix3 normalMatrix(modelViewMatrix);
850 normalMatrix.Invert();
851 normalMatrix.Transpose();
852 WriteDefaultUniform(normalUniformInfo, *ubo, *bindings, normalMatrix);
856 const Vector4& color = node.GetRenderColor(bufferIndex);
857 if(mPremultipledAlphaEnabled)
859 float alpha = color.a * mRenderDataProvider->GetOpacity(bufferIndex);
860 finalColor = Vector4(color.r * alpha, color.g * alpha, color.b * alpha, alpha);
864 finalColor = Vector4(color.r, color.g, color.b, color.a * mRenderDataProvider->GetOpacity(bufferIndex));
866 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::COLOR), *ubo, *bindings, finalColor);
868 // Write uniforms from the uniform map
869 FillUniformBuffer(*program, instruction, *ubo, bindings, uboOffset, bufferIndex);
871 // Write uSize in the end, as it shouldn't be overridable by dynamic properties.
872 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::SIZE), *ubo, *bindings, size);
874 commandBuffer.BindUniformBuffers(*bindings);
879 bool Renderer::WriteDefaultUniform(const Graphics::UniformInfo* uniformInfo, Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const T& data)
881 if(uniformInfo && !uniformInfo->name.empty())
883 WriteUniform(ubo, bindings, *uniformInfo, data);
890 void Renderer::WriteUniform(Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const Graphics::UniformInfo& uniformInfo, const T& data)
892 WriteUniform(ubo, bindings, uniformInfo, &data, sizeof(T));
895 void Renderer::WriteUniform(Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const Graphics::UniformInfo& uniformInfo, const void* data, uint32_t size)
897 ubo.Write(data, size, bindings[uniformInfo.bufferIndex].offset + uniformInfo.offset);
900 void Renderer::FillUniformBuffer(Program& program,
901 const SceneGraph::RenderInstruction& instruction,
902 Render::UniformBuffer& ubo,
903 std::vector<Graphics::UniformBufferBinding>*& outBindings,
905 BufferIndex updateBufferIndex)
907 auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
908 auto uboCount = reflection.GetUniformBlockCount();
911 uint32_t dataOffset = offset;
912 for(auto i = 0u; i < uboCount; ++i)
914 mUniformBufferBindings[i].dataSize = reflection.GetUniformBlockSize(i);
915 mUniformBufferBindings[i].binding = reflection.GetUniformBlockBinding(i);
916 mUniformBufferBindings[i].offset = dataOffset;
918 dataOffset += GetUniformBufferDataAlignment(mUniformBufferBindings[i].dataSize);
919 mUniformBufferBindings[i].buffer = ubo.GetBuffer();
921 for(UniformIndexMappings::Iterator iter = mUniformIndexMap.Begin(),
922 end = mUniformIndexMap.End();
926 // @todo This means parsing the uniform string every frame. Instead, store the array index if present.
927 int arrayIndex = (*iter).arrayIndex;
929 auto uniformInfo = Graphics::UniformInfo{};
930 auto uniformFound = program.GetUniform((*iter).uniformName.GetCString(),
931 (*iter).uniformNameHashNoArray ? (*iter).uniformNameHashNoArray
932 : (*iter).uniformNameHash,
937 auto dst = mUniformBufferBindings[uniformInfo.bufferIndex].offset + uniformInfo.offset;
939 switch((*iter).propertyValue->GetType())
941 case Property::Type::BOOLEAN:
943 ubo.Write(&(*iter).propertyValue->GetBoolean(updateBufferIndex),
945 dst + static_cast<uint32_t>(sizeof(bool)) * arrayIndex);
948 case Property::Type::INTEGER:
950 ubo.Write(&(*iter).propertyValue->GetInteger(updateBufferIndex),
952 dst + static_cast<int32_t>(sizeof(int32_t)) * arrayIndex);
955 case Property::Type::FLOAT:
957 ubo.Write(&(*iter).propertyValue->GetFloat(updateBufferIndex),
959 dst + static_cast<uint32_t>(sizeof(float)) * arrayIndex);
962 case Property::Type::VECTOR2:
964 ubo.Write(&(*iter).propertyValue->GetVector2(updateBufferIndex),
966 dst + static_cast<uint32_t>(sizeof(Vector2)) * arrayIndex);
969 case Property::Type::VECTOR3:
971 ubo.Write(&(*iter).propertyValue->GetVector3(updateBufferIndex),
973 dst + static_cast<uint32_t>(sizeof(Vector3)) * arrayIndex);
976 case Property::Type::VECTOR4:
978 ubo.Write(&(*iter).propertyValue->GetVector4(updateBufferIndex),
980 dst + static_cast<uint32_t>(sizeof(Vector4)) * arrayIndex);
983 case Property::Type::MATRIX:
985 ubo.Write(&(*iter).propertyValue->GetMatrix(updateBufferIndex),
987 dst + static_cast<uint32_t>(sizeof(Matrix)) * arrayIndex);
990 case Property::Type::MATRIX3:
992 // todo: handle data padding properly
995 //const auto& matrix = &(*iter).propertyValue->GetMatrix3(updateBufferIndex);
996 //for(int i = 0; i < 3; ++i)
998 //ubo.Write(&matrix->AsFloat()[i * 3],
999 // sizeof(float) * 3,
1000 // dst + (i * static_cast<uint32_t>(sizeof(Vector4))));
1003 ubo.Write(&(*iter).propertyValue->GetMatrix3(updateBufferIndex),
1005 dst + static_cast<uint32_t>(sizeof(Matrix3)) * arrayIndex);
1015 // write output bindings
1016 outBindings = &mUniformBufferBindings;
1019 offset = dataOffset;
1022 void Renderer::SetSortAttributes(BufferIndex bufferIndex,
1023 SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const
1025 sortAttributes.shader = &(mRenderDataProvider->GetShader());
1026 sortAttributes.geometry = mGeometry;
1029 void Renderer::SetShaderChanged(bool value)
1031 mShaderChanged = value;
1034 bool Renderer::Updated(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider* node)
1042 if(mShaderChanged || mUpdateAttributeLocations || mGeometry->AttributesChanged())
1047 for(const auto& texture : mRenderDataProvider->GetTextures())
1049 if(texture && texture->IsNativeImage())
1055 uint64_t hash = 0xc70f6907UL;
1056 const SceneGraph::CollectedUniformMap& uniformMapNode = node->GetUniformMap(bufferIndex);
1057 for(const auto& uniformProperty : uniformMapNode)
1059 hash = uniformProperty.propertyPtr->Hash(bufferIndex, hash);
1062 const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMap();
1063 const SceneGraph::CollectedUniformMap& uniformMap = uniformMapDataProvider.GetUniformMap(bufferIndex);
1064 for(const auto& uniformProperty : uniformMap)
1066 hash = uniformProperty.propertyPtr->Hash(bufferIndex, hash);
1069 if(mUniformsHash != hash)
1071 mUniformsHash = hash;
1078 Graphics::UniquePtr<Graphics::Pipeline> Renderer::PrepareGraphicsPipeline(
1080 const Dali::Internal::SceneGraph::RenderInstruction& instruction,
1082 Graphics::UniquePtr<Graphics::Pipeline>&& oldPipeline)
1084 Graphics::InputAssemblyState inputAssemblyState{};
1085 Graphics::VertexInputState vertexInputState{};
1086 Graphics::ProgramState programState{};
1087 uint32_t bindingIndex{0u};
1089 if(mUpdateAttributeLocations || mGeometry->AttributesChanged())
1091 mAttributeLocations.Clear();
1092 mUpdateAttributeLocations = true;
1095 auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
1101 for(auto&& vertexBuffer : mGeometry->GetVertexBuffers())
1103 const VertexBuffer::Format& vertexFormat = *vertexBuffer->GetFormat();
1105 vertexInputState.bufferBindings.emplace_back(vertexFormat.size, // stride
1106 Graphics::VertexInputRate::PER_VERTEX);
1108 const uint32_t attributeCount = vertexBuffer->GetAttributeCount();
1109 for(uint32_t i = 0; i < attributeCount; ++i)
1111 if(mUpdateAttributeLocations)
1113 auto attributeName = vertexBuffer->GetAttributeName(i);
1114 int32_t pLocation = reflection.GetVertexAttributeLocation(std::string(attributeName.GetStringView()));
1117 DALI_LOG_WARNING("Attribute not found in the shader: %s\n", attributeName.GetCString());
1119 mAttributeLocations.PushBack(pLocation);
1122 uint32_t location = static_cast<uint32_t>(mAttributeLocations[base + i]);
1124 vertexInputState.attributes.emplace_back(location,
1126 vertexFormat.components[i].offset,
1127 GetPropertyVertexFormat(vertexFormat.components[i].type));
1129 base += attributeCount;
1132 mUpdateAttributeLocations = false;
1135 inputAssemblyState.SetTopology(mGeometry->GetTopology());
1138 programState.SetProgram(program.GetGraphicsProgram());
1140 Graphics::RasterizationState rasterizationState{};
1142 //Set cull face mode
1143 const Dali::Internal::SceneGraph::Camera* cam = instruction.GetCamera();
1144 if(cam->GetReflectionUsed())
1146 auto adjFaceCullingMode = mFaceCullingMode;
1147 switch(mFaceCullingMode)
1149 case FaceCullingMode::Type::FRONT:
1151 adjFaceCullingMode = FaceCullingMode::Type::BACK;
1154 case FaceCullingMode::Type::BACK:
1156 adjFaceCullingMode = FaceCullingMode::Type::FRONT;
1161 // nothing to do, leave culling as it is
1164 rasterizationState.SetCullMode(ConvertCullFace(adjFaceCullingMode));
1168 rasterizationState.SetCullMode(ConvertCullFace(mFaceCullingMode));
1171 rasterizationState.SetFrontFace(Graphics::FrontFace::COUNTER_CLOCKWISE);
1176 switch(mGeometry->GetTopology())
1178 case Graphics::PrimitiveTopology::TRIANGLE_LIST:
1179 case Graphics::PrimitiveTopology::TRIANGLE_STRIP:
1180 case Graphics::PrimitiveTopology::TRIANGLE_FAN:
1181 rasterizationState.SetPolygonMode(Graphics::PolygonMode::FILL);
1183 case Graphics::PrimitiveTopology::LINE_LIST:
1184 case Graphics::PrimitiveTopology::LINE_LOOP:
1185 case Graphics::PrimitiveTopology::LINE_STRIP:
1186 rasterizationState.SetPolygonMode(Graphics::PolygonMode::LINE);
1188 case Graphics::PrimitiveTopology::POINT_LIST:
1189 rasterizationState.SetPolygonMode(Graphics::PolygonMode::POINT);
1193 // @todo How to signal a blend barrier is needed?
1194 //if(mBlendingOptions.IsAdvancedBlendEquationApplied() && mPremultipledAlphaEnabled)
1196 // context.BlendBarrier();
1199 Graphics::ColorBlendState colorBlendState{};
1200 colorBlendState.SetBlendEnable(false);
1204 colorBlendState.SetBlendEnable(true);
1206 Graphics::BlendOp rgbOp = ConvertBlendEquation(mBlendingOptions.GetBlendEquationRgb());
1207 Graphics::BlendOp alphaOp = ConvertBlendEquation(mBlendingOptions.GetBlendEquationRgb());
1208 if(mBlendingOptions.IsAdvancedBlendEquationApplied() && mPremultipledAlphaEnabled)
1210 if(rgbOp != alphaOp)
1212 DALI_LOG_ERROR("Advanced Blend Equation MUST be applied by using BlendEquation.\n");
1218 .SetSrcColorBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendSrcFactorRgb()))
1219 .SetSrcAlphaBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendSrcFactorAlpha()))
1220 .SetDstColorBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendDestFactorRgb()))
1221 .SetDstAlphaBlendFactor(ConvertBlendFactor(mBlendingOptions.GetBlendDestFactorAlpha()))
1222 .SetColorBlendOp(rgbOp)
1223 .SetAlphaBlendOp(alphaOp);
1225 // Blend color is optional and rarely used
1226 Vector4* blendColor = const_cast<Vector4*>(mBlendingOptions.GetBlendColor());
1229 colorBlendState.SetBlendConstants(blendColor->AsFloat());
1233 // Take the program into use so we can send uniforms to it
1234 // @todo Remove this call entirely!
1239 // Create a new pipeline
1240 return mGraphicsController->CreatePipeline(
1241 Graphics::PipelineCreateInfo()
1242 .SetInputAssemblyState(&inputAssemblyState) // Passed as pointers - shallow copy will break. TOO C LIKE
1243 .SetVertexInputState(&vertexInputState)
1244 .SetRasterizationState(&rasterizationState)
1245 .SetColorBlendState(&colorBlendState)
1246 .SetProgramState(&programState)
1247 .SetNextExtension(&mLegacyProgram),
1248 std::move(oldPipeline));
1251 } // namespace Render
1253 } // namespace Internal