2 * Copyright (c) 2022 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/common/render-manager.h>
25 #include <dali/devel-api/threading/thread-pool.h>
26 #include <dali/integration-api/core.h>
28 #include <dali/internal/event/common/scene-impl.h>
30 #include <dali/internal/update/common/scene-graph-scene.h>
31 #include <dali/internal/update/nodes/scene-graph-layer.h>
32 #include <dali/internal/update/render-tasks/scene-graph-camera.h>
34 #include <dali/internal/render/common/render-algorithms.h>
35 #include <dali/internal/render/common/render-debug.h>
36 #include <dali/internal/render/common/render-instruction.h>
37 #include <dali/internal/render/common/render-tracker.h>
38 #include <dali/internal/render/queue/render-queue.h>
39 #include <dali/internal/render/renderers/pipeline-cache.h>
40 #include <dali/internal/render/renderers/render-frame-buffer.h>
41 #include <dali/internal/render/renderers/render-texture.h>
42 #include <dali/internal/render/renderers/shader-cache.h>
43 #include <dali/internal/render/renderers/uniform-buffer-manager.h>
44 #include <dali/internal/render/renderers/uniform-buffer-view-pool.h>
45 #include <dali/internal/render/shaders/program-controller.h>
55 #if defined(DEBUG_ENABLED)
58 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER");
59 } // unnamed namespace
64 inline Graphics::Rect2D RecalculateScissorArea(Graphics::Rect2D scissorArea, int orientation, Rect<int32_t> viewportRect)
66 Graphics::Rect2D newScissorArea;
70 newScissorArea.x = viewportRect.height - (scissorArea.y + scissorArea.height);
71 newScissorArea.y = scissorArea.x;
72 newScissorArea.width = scissorArea.height;
73 newScissorArea.height = scissorArea.width;
75 else if(orientation == 180)
77 newScissorArea.x = viewportRect.width - (scissorArea.x + scissorArea.width);
78 newScissorArea.y = viewportRect.height - (scissorArea.y + scissorArea.height);
79 newScissorArea.width = scissorArea.width;
80 newScissorArea.height = scissorArea.height;
82 else if(orientation == 270)
84 newScissorArea.x = scissorArea.y;
85 newScissorArea.y = viewportRect.width - (scissorArea.x + scissorArea.width);
86 newScissorArea.width = scissorArea.height;
87 newScissorArea.height = scissorArea.width;
91 newScissorArea.x = scissorArea.x;
92 newScissorArea.y = scissorArea.y;
93 newScissorArea.width = scissorArea.width;
94 newScissorArea.height = scissorArea.height;
96 return newScissorArea;
101 * Structure to contain internal data
103 struct RenderManager::Impl
105 Impl(Graphics::Controller& graphicsController,
106 Integration::DepthBufferAvailable depthBufferAvailableParam,
107 Integration::StencilBufferAvailable stencilBufferAvailableParam,
108 Integration::PartialUpdateAvailable partialUpdateAvailableParam)
109 : graphicsController(graphicsController),
111 renderAlgorithms(graphicsController),
113 renderBufferIndex(SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX),
117 frameBufferContainer(),
118 lastFrameWasRendered(false),
119 programController(graphicsController),
120 shaderCache(graphicsController),
121 depthBufferAvailable(depthBufferAvailableParam),
122 stencilBufferAvailable(stencilBufferAvailableParam),
123 partialUpdateAvailable(partialUpdateAvailableParam)
125 // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
126 threadPool = std::make_unique<Dali::ThreadPool>();
127 threadPool->Initialize(1u);
129 uniformBufferManager = std::make_unique<Render::UniformBufferManager>(&graphicsController);
130 pipelineCache = std::make_unique<Render::PipelineCache>(graphicsController);
135 threadPool.reset(nullptr); // reset now to maintain correct destruction order
138 void AddRenderTracker(Render::RenderTracker* renderTracker)
140 DALI_ASSERT_DEBUG(renderTracker != nullptr);
141 mRenderTrackers.PushBack(renderTracker);
144 void RemoveRenderTracker(Render::RenderTracker* renderTracker)
146 mRenderTrackers.EraseObject(renderTracker);
149 void UpdateTrackers()
151 for(auto&& iter : mRenderTrackers)
153 iter->PollSyncObject();
157 // the order is important for destruction,
158 Graphics::Controller& graphicsController;
159 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
161 std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
163 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
165 uint32_t frameCount; ///< The current frame count
166 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
168 OwnerContainer<Render::Renderer*> rendererContainer; ///< List of owned renderers
169 OwnerContainer<Render::Sampler*> samplerContainer; ///< List of owned samplers
170 OwnerContainer<Render::Texture*> textureContainer; ///< List of owned textures
171 OwnerContainer<Render::FrameBuffer*> frameBufferContainer; ///< List of owned framebuffers
172 OwnerContainer<Render::VertexBuffer*> vertexBufferContainer; ///< List of owned vertex buffers
173 OwnerContainer<Render::Geometry*> geometryContainer; ///< List of owned Geometries
175 bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
177 OwnerContainer<Render::RenderTracker*> mRenderTrackers; ///< List of render trackers
179 ProgramController programController; ///< Owner of the programs
180 Render::ShaderCache shaderCache; ///< The cache for the graphics shaders
182 std::unique_ptr<Render::UniformBufferManager> uniformBufferManager; ///< The uniform buffer manager
183 std::unique_ptr<Render::PipelineCache> pipelineCache;
185 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
186 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
187 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
189 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
190 Vector<Graphics::Texture*> boundTextures; ///< The textures bound for rendering
191 Vector<Graphics::Texture*> textureDependencyList; ///< The dependency list of bound textures
193 bool commandBufferSubmitted{false};
196 RenderManager* RenderManager::New(Graphics::Controller& graphicsController,
197 Integration::DepthBufferAvailable depthBufferAvailable,
198 Integration::StencilBufferAvailable stencilBufferAvailable,
199 Integration::PartialUpdateAvailable partialUpdateAvailable)
201 auto* manager = new RenderManager;
202 manager->mImpl = new Impl(graphicsController,
203 depthBufferAvailable,
204 stencilBufferAvailable,
205 partialUpdateAvailable);
209 RenderManager::RenderManager()
214 RenderManager::~RenderManager()
219 RenderQueue& RenderManager::GetRenderQueue()
221 return mImpl->renderQueue;
224 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
228 void RenderManager::AddRenderer(OwnerPointer<Render::Renderer>& renderer)
230 // Initialize the renderer as we are now in render thread
231 renderer->Initialize(mImpl->graphicsController, mImpl->programController, mImpl->shaderCache, *(mImpl->uniformBufferManager.get()), *(mImpl->pipelineCache.get()));
233 mImpl->rendererContainer.PushBack(renderer.Release());
236 void RenderManager::RemoveRenderer(Render::Renderer* renderer)
238 mImpl->rendererContainer.EraseObject(renderer);
241 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
243 sampler->Initialize(mImpl->graphicsController);
244 mImpl->samplerContainer.PushBack(sampler.Release());
247 void RenderManager::RemoveSampler(Render::Sampler* sampler)
249 mImpl->samplerContainer.EraseObject(sampler);
252 void RenderManager::AddTexture(OwnerPointer<Render::Texture>& texture)
254 texture->Initialize(mImpl->graphicsController);
255 mImpl->textureContainer.PushBack(texture.Release());
258 void RenderManager::RemoveTexture(Render::Texture* texture)
260 DALI_ASSERT_DEBUG(NULL != texture);
262 // Find the texture, use std::find so we can do the erase safely
263 auto iter = std::find(mImpl->textureContainer.begin(), mImpl->textureContainer.end(), texture);
265 if(iter != mImpl->textureContainer.end())
268 mImpl->textureContainer.Erase(iter); // Texture found; now destroy it
272 void RenderManager::UploadTexture(Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params)
274 texture->Upload(pixelData, params);
277 void RenderManager::GenerateMipmaps(Render::Texture* texture)
279 texture->GenerateMipmaps();
282 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
284 sampler->SetFilterMode(static_cast<Dali::FilterMode::Type>(minFilterMode),
285 static_cast<Dali::FilterMode::Type>(magFilterMode));
288 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
290 sampler->SetWrapMode(static_cast<Dali::WrapMode::Type>(rWrapMode),
291 static_cast<Dali::WrapMode::Type>(sWrapMode),
292 static_cast<Dali::WrapMode::Type>(tWrapMode));
295 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
297 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
298 mImpl->frameBufferContainer.PushBack(frameBufferPtr);
299 frameBufferPtr->Initialize(mImpl->graphicsController);
302 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
304 DALI_ASSERT_DEBUG(nullptr != frameBuffer);
306 // Find the framebuffer, use std:find so we can safely do the erase
307 auto iter = std::find(mImpl->frameBufferContainer.begin(), mImpl->frameBufferContainer.end(), frameBuffer);
309 if(iter != mImpl->frameBufferContainer.end())
311 frameBuffer->Destroy();
312 mImpl->frameBufferContainer.Erase(iter); // frameBuffer found; now destroy it
316 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
318 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
319 mImpl->sceneContainer.push_back(scene);
322 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
324 auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
325 if(iter != mImpl->sceneContainer.end())
327 mImpl->sceneContainer.erase(iter);
331 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
333 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
336 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
338 frameBuffer->AttachColorTexture(texture, mipmapLevel, layer);
341 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
343 frameBuffer->AttachDepthTexture(texture, mipmapLevel);
346 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
348 frameBuffer->AttachDepthStencilTexture(texture, mipmapLevel);
351 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
353 mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
356 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
358 mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
361 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
363 vertexBuffer->SetFormat(format.Release());
366 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
368 vertexBuffer->SetData(data.Release(), size);
371 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Dali::Vector<uint16_t>& indices)
373 geometry->SetIndexBuffer(indices);
376 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
378 mImpl->geometryContainer.PushBack(geometry.Release());
381 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
383 auto iter = std::find(mImpl->geometryContainer.begin(), mImpl->geometryContainer.end(), geometry);
385 if(iter != mImpl->geometryContainer.end())
387 mImpl->geometryContainer.Erase(iter);
391 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
393 DALI_ASSERT_DEBUG(nullptr != geometry);
396 for(auto&& iter : mImpl->geometryContainer)
400 iter->AddVertexBuffer(vertexBuffer);
406 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
408 DALI_ASSERT_DEBUG(nullptr != geometry);
411 for(auto&& iter : mImpl->geometryContainer)
415 iter->RemoveVertexBuffer(vertexBuffer);
421 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
423 geometry->SetType(Render::Geometry::Type(geometryType));
426 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
428 mImpl->AddRenderTracker(renderTracker);
431 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
433 mImpl->RemoveRenderTracker(renderTracker);
436 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear)
438 DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
441 mImpl->uniformBufferManager->GetUniformBufferViewPool(mImpl->renderBufferIndex)->Rollback();
443 // Increment the frame count at the beginning of each frame
446 // Process messages queued during previous update
447 mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
450 for(auto& i : mImpl->sceneContainer)
452 count += i->GetRenderInstructions().Count(mImpl->renderBufferIndex);
455 const bool haveInstructions = count > 0u;
457 DALI_LOG_INFO(gLogFilter, Debug::General, "Render: haveInstructions(%s) || mImpl->lastFrameWasRendered(%s) || forceClear(%s)\n", haveInstructions ? "true" : "false", mImpl->lastFrameWasRendered ? "true" : "false", forceClear ? "true" : "false");
459 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
460 if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
462 DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
464 // Upload the geometries
465 for(auto&& geom : mImpl->geometryContainer)
467 geom->Upload(mImpl->graphicsController);
471 mImpl->commandBufferSubmitted = false;
474 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
476 if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
481 Internal::Scene& sceneInternal = GetImplementation(scene);
482 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
484 if(sceneObject->IsRenderingSkipped())
486 // We don't need to calculate dirty rects
490 class DamagedRectsCleaner
493 explicit DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects, Rect<int>& surfaceRect)
494 : mDamagedRects(damagedRects),
495 mSurfaceRect(surfaceRect),
500 void SetCleanOnReturn(bool cleanOnReturn)
502 mCleanOnReturn = cleanOnReturn;
505 ~DamagedRectsCleaner()
509 mDamagedRects.clear();
510 mDamagedRects.push_back(mSurfaceRect);
515 std::vector<Rect<int>>& mDamagedRects;
516 Rect<int> mSurfaceRect;
520 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
522 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
523 DamagedRectsCleaner damagedRectCleaner(damagedRects, surfaceRect);
525 // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
526 // so you don't need to sort: std::stable_sort(itemsDirtyRects.begin(), itemsDirtyRects.end());
527 std::vector<DirtyRect>& itemsDirtyRects = sceneObject->GetItemsDirtyRects();
528 for(DirtyRect& dirtyRect : itemsDirtyRects)
530 dirtyRect.visited = false;
533 uint32_t instructionCount = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
534 for(uint32_t i = 0; i < instructionCount; ++i)
536 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
538 if(instruction.mFrameBuffer)
540 return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
543 const Camera* camera = instruction.GetCamera();
544 if(camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
546 const Node* node = instruction.GetCamera()->GetNode();
551 Quaternion orientation;
552 node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
554 Vector3 orientationAxis;
555 Radian orientationAngle;
556 orientation.ToAxisAngle(orientationAxis, orientationAngle);
558 if(position.x > Math::MACHINE_EPSILON_10000 ||
559 position.y > Math::MACHINE_EPSILON_10000 ||
560 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
561 orientationAngle != ANGLE_180 ||
562 scale != Vector3(1.0f, 1.0f, 1.0f))
573 Rect<int32_t> viewportRect;
574 if(instruction.mIsViewportSet)
576 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
577 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
578 if(viewportRect.IsEmpty() || !viewportRect.IsValid())
580 return; // just skip funny use cases for now, empty viewport means it is set somewhere else
585 viewportRect = surfaceRect;
588 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
589 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
590 if(viewMatrix && projectionMatrix)
592 const RenderListContainer::SizeType count = instruction.RenderListCount();
593 for(RenderListContainer::SizeType index = 0u; index < count; ++index)
595 const RenderList* renderList = instruction.GetRenderList(index);
598 if(!renderList->IsEmpty())
600 const std::size_t listCount = renderList->Count();
601 for(uint32_t listIndex = 0u; listIndex < listCount; ++listIndex)
603 RenderItem& item = renderList->GetItem(listIndex);
604 // If the item does 3D transformation, do early exit and clean the damaged rect array
605 if(item.mUpdateArea == Vector4::ZERO)
611 DirtyRect dirtyRect(item.mNode, item.mRenderer, rect);
612 // If the item refers to updated node or renderer.
613 if(item.mIsUpdated ||
615 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
617 item.mIsUpdated = false;
619 rect = RenderItem::CalculateViewportSpaceAABB(item.mModelViewMatrix, Vector3(item.mUpdateArea.x, item.mUpdateArea.y, 0.0f), Vector3(item.mUpdateArea.z, item.mUpdateArea.w, 0.0f), viewportRect.width, viewportRect.height);
620 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
622 const int left = rect.x;
623 const int top = rect.y;
624 const int right = rect.x + rect.width;
625 const int bottom = rect.y + rect.height;
626 rect.x = (left / 16) * 16;
627 rect.y = (top / 16) * 16;
628 rect.width = ((right + 16) / 16) * 16 - rect.x;
629 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
631 // Found valid dirty rect.
632 dirtyRect.rect = rect;
633 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
635 if(dirtyRectPos != itemsDirtyRects.end() && dirtyRectPos->node == item.mNode && dirtyRectPos->renderer == item.mRenderer)
637 // Same item, merge it with the previous rect
638 rect.Merge(dirtyRectPos->rect);
641 dirtyRectPos->visited = true;
642 dirtyRectPos->rect = dirtyRect.rect;
646 // Else, just insert the new dirtyrect in the correct position
647 itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
650 damagedRects.push_back(rect);
655 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
656 // 2. Mark the related dirty rects as visited so they will not be removed below.
657 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
658 if(dirtyRectPos != itemsDirtyRects.end() && dirtyRectPos->node == item.mNode && dirtyRectPos->renderer == item.mRenderer)
660 dirtyRectPos->visited = true;
670 // Check removed nodes or removed renderers dirty rects
671 auto i = itemsDirtyRects.begin();
672 auto j = itemsDirtyRects.begin();
673 while(i != itemsDirtyRects.end())
681 Rect<int>& dirtRect = i->rect;
682 damagedRects.push_back(dirtRect);
687 itemsDirtyRects.resize(j - itemsDirtyRects.begin());
688 damagedRectCleaner.SetCleanOnReturn(false);
690 // Reset updated flag from the root
691 Layer* root = sceneObject->GetRoot();
694 root->SetUpdatedTree(false);
698 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
700 SceneGraph::Scene* sceneObject = GetImplementation(scene).GetSceneObject();
701 Rect<int> clippingRect = sceneObject->GetSurfaceRect();
703 RenderScene(status, scene, renderToFbo, clippingRect);
706 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
708 if(mImpl->partialUpdateAvailable == Integration::PartialUpdateAvailable::TRUE && !renderToFbo && clippingRect.IsEmpty())
710 // ClippingRect is empty. Skip rendering
714 // Reset main algorithms command buffer
715 mImpl->renderAlgorithms.ResetCommandBuffer();
717 auto mainCommandBuffer = mImpl->renderAlgorithms.GetMainCommandBuffer();
719 Internal::Scene& sceneInternal = GetImplementation(scene);
720 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
722 uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
724 std::vector<Graphics::RenderTarget*> targetstoPresent;
726 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
727 if(clippingRect == surfaceRect)
729 // Full rendering case
730 // Make clippingRect empty because we're doing full rendering now if the clippingRect is empty.
731 // To reduce side effects, keep this logic now.
732 clippingRect = Rect<int>();
735 // Prepare to lock and map standalone uniform buffer.
736 mImpl->uniformBufferManager->ReadyToLockUniformBuffer(mImpl->renderBufferIndex);
738 for(uint32_t i = 0; i < count; ++i)
740 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
742 if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
747 // Mark that we will require a post-render step to be performed (includes swap-buffers).
748 status.SetNeedsPostRender(true);
750 Rect<int32_t> viewportRect;
752 int32_t surfaceOrientation = sceneObject->GetSurfaceOrientation();
754 // @todo Should these be part of scene?
755 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
756 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
758 Graphics::RenderTarget* currentRenderTarget = nullptr;
759 Graphics::RenderPass* currentRenderPass = nullptr;
760 std::vector<Graphics::ClearValue> currentClearValues{};
762 if(instruction.mFrameBuffer)
764 // Ensure graphics framebuffer is created, bind attachments and create render passes
765 // Only happens once per framebuffer. If the create fails, e.g. no attachments yet,
766 // then don't render to this framebuffer.
767 if(!instruction.mFrameBuffer->GetGraphicsObject())
769 const bool created = instruction.mFrameBuffer->CreateGraphicsObjects();
776 auto& clearValues = instruction.mFrameBuffer->GetGraphicsRenderPassClearValues();
778 // Set the clear color for first color attachment
779 if(instruction.mIsClearColorSet && !clearValues.empty())
781 clearValues[0].color = {
782 instruction.mClearColor.r,
783 instruction.mClearColor.g,
784 instruction.mClearColor.b,
785 instruction.mClearColor.a};
788 currentClearValues = clearValues;
790 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
793 currentRenderTarget = instruction.mFrameBuffer->GetGraphicsRenderTarget();
794 currentRenderPass = instruction.mFrameBuffer->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
796 else // no framebuffer
799 auto& clearValues = sceneObject->GetGraphicsRenderPassClearValues();
801 if(instruction.mIsClearColorSet)
803 clearValues[0].color = {
804 instruction.mClearColor.r,
805 instruction.mClearColor.g,
806 instruction.mClearColor.b,
807 instruction.mClearColor.a};
810 currentClearValues = clearValues;
812 // @todo SceneObject should already have the depth clear / stencil clear in the clearValues array.
813 // if the window has a depth/stencil buffer.
814 if((depthBufferAvailable == Integration::DepthBufferAvailable::TRUE ||
815 stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE) &&
816 (currentClearValues.size() <= 1))
818 currentClearValues.emplace_back();
819 currentClearValues.back().depthStencil.depth = 0;
820 currentClearValues.back().depthStencil.stencil = 0;
823 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
825 currentRenderTarget = sceneObject->GetSurfaceRenderTarget();
826 currentRenderPass = sceneObject->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
829 targetstoPresent.emplace_back(currentRenderTarget);
831 // reset the program matrices for all programs once per frame
832 // this ensures we will set view and projection matrix once per program per camera
833 mImpl->programController.ResetProgramMatrices();
835 if(instruction.mFrameBuffer)
837 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
838 for(unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
840 mImpl->textureDependencyList.PushBack(instruction.mFrameBuffer->GetTexture(i0));
844 if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
846 // Offscreen buffer rendering
847 if(instruction.mIsViewportSet)
849 // For Viewport the lower-left corner is (0,0)
850 const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
851 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
855 viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
857 surfaceOrientation = 0;
859 else // No Offscreen frame buffer rendering
861 // Check whether a viewport is specified, otherwise the full surface size is used
862 if(instruction.mIsViewportSet)
864 // For Viewport the lower-left corner is (0,0)
865 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
866 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
870 viewportRect = surfaceRect;
874 // Set surface orientation
875 // @todo Inform graphics impl by another route.
876 // was: mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
878 /*** Clear region of framebuffer or surface before drawing ***/
879 bool clearFullFrameRect = (surfaceRect == viewportRect);
880 if(instruction.mFrameBuffer != nullptr)
882 Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
883 clearFullFrameRect = (frameRect == viewportRect);
886 if(!clippingRect.IsEmpty())
888 if(!clippingRect.Intersect(viewportRect))
890 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
891 clippingRect = Rect<int>();
893 clearFullFrameRect = false;
896 Graphics::Rect2D scissorArea{viewportRect.x, viewportRect.y, uint32_t(viewportRect.width), uint32_t(viewportRect.height)};
897 if(instruction.mIsClearColorSet)
899 if(!clearFullFrameRect)
901 if(!clippingRect.IsEmpty())
903 scissorArea = {clippingRect.x, clippingRect.y, uint32_t(clippingRect.width), uint32_t(clippingRect.height)};
908 // Scissor's value should be set based on the default system coordinates.
909 // When the surface is rotated, the input values already were set with the rotated angle.
910 // So, re-calculation is needed.
911 scissorArea = RecalculateScissorArea(scissorArea, surfaceOrientation, viewportRect);
914 mainCommandBuffer->BeginRenderPass(
920 mainCommandBuffer->SetViewport({float(viewportRect.x),
921 float(viewportRect.y),
922 float(viewportRect.width),
923 float(viewportRect.height)});
925 // Clear the list of bound textures
926 mImpl->boundTextures.Clear();
928 mImpl->renderAlgorithms.ProcessRenderInstruction(
930 mImpl->renderBufferIndex,
931 depthBufferAvailable,
932 stencilBufferAvailable,
933 mImpl->boundTextures,
938 Graphics::SyncObject* syncObject{nullptr};
939 // If the render instruction has an associated render tracker (owned separately)
940 // and framebuffer, create a one shot sync object, and use it to determine when
941 // the render pass has finished executing on GPU.
942 if(instruction.mRenderTracker && instruction.mFrameBuffer)
944 syncObject = instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController);
945 instruction.mRenderTracker = nullptr;
947 mainCommandBuffer->EndRenderPass(syncObject);
950 // Unlock standalone uniform buffer.
951 mImpl->uniformBufferManager->UnlockUniformBuffer(mImpl->renderBufferIndex);
953 mImpl->renderAlgorithms.SubmitCommandBuffer();
954 mImpl->commandBufferSubmitted = true;
956 std::sort(targetstoPresent.begin(), targetstoPresent.end());
958 Graphics::RenderTarget* rt = nullptr;
959 for(auto& target : targetstoPresent)
963 mImpl->graphicsController.PresentRenderTarget(target);
969 void RenderManager::PostRender()
971 if(!mImpl->commandBufferSubmitted)
973 // Rendering is skipped but there may be pending tasks. Flush them.
974 Graphics::SubmitInfo submitInfo;
975 submitInfo.cmdBuffer.clear(); // Only flush
976 submitInfo.flags = 0 | Graphics::SubmitFlagBits::FLUSH;
977 mImpl->graphicsController.SubmitCommandBuffers(submitInfo);
979 mImpl->commandBufferSubmitted = true;
982 // Notify RenderGeometries that rendering has finished
983 for(auto&& iter : mImpl->geometryContainer)
985 iter->OnRenderFinished();
988 mImpl->UpdateTrackers();
991 for(auto& scene : mImpl->sceneContainer)
993 count += scene->GetRenderInstructions().Count(mImpl->renderBufferIndex);
996 const bool haveInstructions = count > 0u;
998 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
999 mImpl->lastFrameWasRendered = haveInstructions;
1002 * The rendering has finished; swap to the next buffer.
1003 * Ideally the update has just finished using this buffer; otherwise the render thread
1004 * should block until the update has finished.
1006 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1008 DALI_PRINT_RENDER_END();
1011 } // namespace SceneGraph
1013 } // namespace Internal