2 * Copyright (c) 2023 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <dali/internal/render/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/common/owner-key-container.h>
36 #include <dali/internal/render/common/render-algorithms.h>
37 #include <dali/internal/render/common/render-debug.h>
38 #include <dali/internal/render/common/render-instruction.h>
39 #include <dali/internal/render/common/render-tracker.h>
40 #include <dali/internal/render/queue/render-queue.h>
41 #include <dali/internal/render/renderers/pipeline-cache.h>
42 #include <dali/internal/render/renderers/render-frame-buffer.h>
43 #include <dali/internal/render/renderers/render-texture.h>
44 #include <dali/internal/render/renderers/shader-cache.h>
45 #include <dali/internal/render/renderers/uniform-buffer-manager.h>
46 #include <dali/internal/render/renderers/uniform-buffer-view-pool.h>
47 #include <dali/internal/render/shaders/program-controller.h>
57 #if defined(DEBUG_ENABLED)
60 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER");
61 } // unnamed namespace
66 inline Graphics::Rect2D RecalculateScissorArea(Graphics::Rect2D scissorArea, int orientation, Rect<int32_t> viewportRect)
68 Graphics::Rect2D newScissorArea;
72 newScissorArea.x = viewportRect.height - (scissorArea.y + scissorArea.height);
73 newScissorArea.y = scissorArea.x;
74 newScissorArea.width = scissorArea.height;
75 newScissorArea.height = scissorArea.width;
77 else if(orientation == 180)
79 newScissorArea.x = viewportRect.width - (scissorArea.x + scissorArea.width);
80 newScissorArea.y = viewportRect.height - (scissorArea.y + scissorArea.height);
81 newScissorArea.width = scissorArea.width;
82 newScissorArea.height = scissorArea.height;
84 else if(orientation == 270)
86 newScissorArea.x = scissorArea.y;
87 newScissorArea.y = viewportRect.width - (scissorArea.x + scissorArea.width);
88 newScissorArea.width = scissorArea.height;
89 newScissorArea.height = scissorArea.width;
93 newScissorArea.x = scissorArea.x;
94 newScissorArea.y = scissorArea.y;
95 newScissorArea.width = scissorArea.width;
96 newScissorArea.height = scissorArea.height;
98 return newScissorArea;
103 * Structure to contain internal data
105 struct RenderManager::Impl
107 Impl(Graphics::Controller& graphicsController,
108 Integration::DepthBufferAvailable depthBufferAvailableParam,
109 Integration::StencilBufferAvailable stencilBufferAvailableParam,
110 Integration::PartialUpdateAvailable partialUpdateAvailableParam)
111 : graphicsController(graphicsController),
112 renderAlgorithms(graphicsController),
113 programController(graphicsController),
114 shaderCache(graphicsController),
115 depthBufferAvailable(depthBufferAvailableParam),
116 stencilBufferAvailable(stencilBufferAvailableParam),
117 partialUpdateAvailable(partialUpdateAvailableParam)
119 // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
120 threadPool = std::make_unique<Dali::ThreadPool>();
121 threadPool->Initialize(1u);
123 uniformBufferManager = std::make_unique<Render::UniformBufferManager>(&graphicsController);
124 pipelineCache = std::make_unique<Render::PipelineCache>(graphicsController);
129 threadPool.reset(nullptr); // reset now to maintain correct destruction order
132 void AddRenderTracker(Render::RenderTracker* renderTracker)
134 DALI_ASSERT_DEBUG(renderTracker != nullptr);
135 mRenderTrackers.PushBack(renderTracker);
138 void RemoveRenderTracker(Render::RenderTracker* renderTracker)
140 mRenderTrackers.EraseObject(renderTracker);
143 void UpdateTrackers()
145 for(auto&& iter : mRenderTrackers)
147 iter->PollSyncObject();
151 // the order is important for destruction,
152 Graphics::Controller& graphicsController;
153 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
154 std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
155 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
157 OwnerContainer<Render::Sampler*> samplerContainer; ///< List of owned samplers
158 OwnerContainer<Render::FrameBuffer*> frameBufferContainer; ///< List of owned framebuffers
159 OwnerContainer<Render::VertexBuffer*> vertexBufferContainer; ///< List of owned vertex buffers
160 OwnerContainer<Render::Geometry*> geometryContainer; ///< List of owned Geometries
161 OwnerContainer<Render::RenderTracker*> mRenderTrackers; ///< List of render trackers
162 OwnerKeyContainer<Render::Renderer> rendererContainer; ///< List of owned renderers
163 OwnerKeyContainer<Render::Texture> textureContainer; ///< List of owned textures
165 ProgramController programController; ///< Owner of the programs
166 Render::ShaderCache shaderCache; ///< The cache for the graphics shaders
168 std::unique_ptr<Render::UniformBufferManager> uniformBufferManager; ///< The uniform buffer manager
169 std::unique_ptr<Render::PipelineCache> pipelineCache;
171 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
172 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
173 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
175 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
176 Vector<Graphics::Texture*> boundTextures; ///< The textures bound for rendering
177 Vector<Graphics::Texture*> textureDependencyList; ///< The dependency list of bound textures
179 uint32_t frameCount{0u}; ///< The current frame count
180 BufferIndex renderBufferIndex{SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX}; ///< The index of the buffer to read from; this is opposite of the "update" buffer
182 bool lastFrameWasRendered{false}; ///< Keeps track of the last frame being rendered due to having render instructions
183 bool commandBufferSubmitted{false};
186 RenderManager* RenderManager::New(Graphics::Controller& graphicsController,
187 Integration::DepthBufferAvailable depthBufferAvailable,
188 Integration::StencilBufferAvailable stencilBufferAvailable,
189 Integration::PartialUpdateAvailable partialUpdateAvailable)
191 auto* manager = new RenderManager;
192 manager->mImpl = new Impl(graphicsController,
193 depthBufferAvailable,
194 stencilBufferAvailable,
195 partialUpdateAvailable);
199 RenderManager::RenderManager()
204 RenderManager::~RenderManager()
209 RenderQueue& RenderManager::GetRenderQueue()
211 return mImpl->renderQueue;
214 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
218 void RenderManager::AddRenderer(const Render::RendererKey& renderer)
220 // Initialize the renderer as we are now in render thread
221 renderer->Initialize(mImpl->graphicsController, mImpl->programController, mImpl->shaderCache, *(mImpl->uniformBufferManager.get()), *(mImpl->pipelineCache.get()));
223 mImpl->rendererContainer.PushBack(renderer);
226 void RenderManager::RemoveRenderer(const Render::RendererKey& renderer)
228 mImpl->rendererContainer.EraseKey(renderer);
231 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
233 sampler->Initialize(mImpl->graphicsController);
234 mImpl->samplerContainer.PushBack(sampler.Release());
237 void RenderManager::RemoveSampler(Render::Sampler* sampler)
239 mImpl->samplerContainer.EraseObject(sampler);
242 void RenderManager::AddTexture(const Render::TextureKey& textureKey)
244 DALI_ASSERT_DEBUG(textureKey && "Trying to add empty texture key");
246 textureKey->Initialize(mImpl->graphicsController);
247 mImpl->textureContainer.PushBack(textureKey);
250 void RenderManager::RemoveTexture(const Render::TextureKey& textureKey)
252 DALI_ASSERT_DEBUG(textureKey && "Trying to remove empty texture key");
254 // Find the texture, use std::find so we can do the erase safely
255 auto iter = std::find(mImpl->textureContainer.begin(), mImpl->textureContainer.end(), textureKey);
257 if(iter != mImpl->textureContainer.end())
259 textureKey->Destroy();
260 mImpl->textureContainer.Erase(iter); // Texture found; now destroy it
264 void RenderManager::UploadTexture(const Render::TextureKey& textureKey, PixelDataPtr pixelData, const Texture::UploadParams& params)
266 DALI_ASSERT_DEBUG(textureKey && "Trying to upload to empty texture key");
267 textureKey->Upload(pixelData, params);
270 void RenderManager::GenerateMipmaps(const Render::TextureKey& textureKey)
272 DALI_ASSERT_DEBUG(textureKey && "Trying to generate mipmaps on empty texture key");
273 textureKey->GenerateMipmaps();
276 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
278 sampler->SetFilterMode(static_cast<Dali::FilterMode::Type>(minFilterMode),
279 static_cast<Dali::FilterMode::Type>(magFilterMode));
282 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
284 sampler->SetWrapMode(static_cast<Dali::WrapMode::Type>(rWrapMode),
285 static_cast<Dali::WrapMode::Type>(sWrapMode),
286 static_cast<Dali::WrapMode::Type>(tWrapMode));
289 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
291 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
292 mImpl->frameBufferContainer.PushBack(frameBufferPtr);
293 frameBufferPtr->Initialize(mImpl->graphicsController);
296 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
298 DALI_ASSERT_DEBUG(nullptr != frameBuffer);
300 // Find the framebuffer, use std:find so we can safely do the erase
301 auto iter = std::find(mImpl->frameBufferContainer.begin(), mImpl->frameBufferContainer.end(), frameBuffer);
303 if(iter != mImpl->frameBufferContainer.end())
305 frameBuffer->Destroy();
306 mImpl->frameBufferContainer.Erase(iter); // frameBuffer found; now destroy it
310 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
312 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
313 mImpl->sceneContainer.push_back(scene);
316 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
318 auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
319 if(iter != mImpl->sceneContainer.end())
321 mImpl->sceneContainer.erase(iter);
325 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
327 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
330 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
332 frameBuffer->AttachColorTexture(texture, mipmapLevel, layer);
335 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
337 frameBuffer->AttachDepthTexture(texture, mipmapLevel);
340 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
342 frameBuffer->AttachDepthStencilTexture(texture, mipmapLevel);
345 void RenderManager::SetMultiSamplingLevelToFrameBuffer(Render::FrameBuffer* frameBuffer, uint8_t multiSamplingLevel)
347 frameBuffer->SetMultiSamplingLevel(multiSamplingLevel);
350 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
352 mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
355 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
357 mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
360 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
362 vertexBuffer->SetFormat(format.Release());
365 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
367 vertexBuffer->SetData(data.Release(), size);
370 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Dali::Vector<uint16_t>& indices)
372 geometry->SetIndexBuffer(indices);
375 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
377 mImpl->geometryContainer.PushBack(geometry.Release());
380 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
382 auto iter = std::find(mImpl->geometryContainer.begin(), mImpl->geometryContainer.end(), geometry);
384 if(iter != mImpl->geometryContainer.end())
386 mImpl->geometryContainer.Erase(iter);
390 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
392 DALI_ASSERT_DEBUG(nullptr != geometry);
395 for(auto&& iter : mImpl->geometryContainer)
399 iter->AddVertexBuffer(vertexBuffer);
405 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
407 DALI_ASSERT_DEBUG(nullptr != geometry);
410 for(auto&& iter : mImpl->geometryContainer)
414 iter->RemoveVertexBuffer(vertexBuffer);
420 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
422 geometry->SetType(Render::Geometry::Type(geometryType));
425 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
427 mImpl->AddRenderTracker(renderTracker);
430 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
432 mImpl->RemoveRenderTracker(renderTracker);
435 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear)
437 DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
440 mImpl->uniformBufferManager->GetUniformBufferViewPool(mImpl->renderBufferIndex)->Rollback();
442 // Increment the frame count at the beginning of each frame
445 // Process messages queued during previous update
446 mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
449 for(auto& i : mImpl->sceneContainer)
451 count += i->GetRenderInstructions().Count(mImpl->renderBufferIndex);
454 const bool haveInstructions = count > 0u;
456 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");
458 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
459 if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
461 DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
463 // Upload the geometries
464 for(auto&& geom : mImpl->geometryContainer)
466 geom->Upload(mImpl->graphicsController);
470 mImpl->commandBufferSubmitted = false;
473 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
475 if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
480 Internal::Scene& sceneInternal = GetImplementation(scene);
481 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
483 if(sceneObject->IsRenderingSkipped())
485 // We don't need to calculate dirty rects
489 class DamagedRectsCleaner
492 explicit DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects, Rect<int>& surfaceRect)
493 : mDamagedRects(damagedRects),
494 mSurfaceRect(surfaceRect),
499 void SetCleanOnReturn(bool cleanOnReturn)
501 mCleanOnReturn = cleanOnReturn;
504 ~DamagedRectsCleaner()
508 mDamagedRects.clear();
509 mDamagedRects.push_back(mSurfaceRect);
514 std::vector<Rect<int>>& mDamagedRects;
515 Rect<int> mSurfaceRect;
519 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
521 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
522 DamagedRectsCleaner damagedRectCleaner(damagedRects, surfaceRect);
523 bool cleanDamagedRect = false;
525 // Mark previous dirty rects in the std::unordered_map.
526 Scene::ItemsDirtyRectsContainer& itemsDirtyRects = sceneObject->GetItemsDirtyRects();
527 for(auto& dirtyRectPair : itemsDirtyRects)
529 dirtyRectPair.second.visited = false;
532 uint32_t instructionCount = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
533 for(uint32_t i = 0; i < instructionCount; ++i)
535 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
537 if(instruction.mFrameBuffer)
539 cleanDamagedRect = true;
540 continue; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
543 const Camera* camera = instruction.GetCamera();
544 if(camera && camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
548 Quaternion orientation;
549 camera->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
551 Vector3 orientationAxis;
552 Radian orientationAngle;
553 orientation.ToAxisAngle(orientationAxis, orientationAngle);
555 if(position.x > Math::MACHINE_EPSILON_10000 ||
556 position.y > Math::MACHINE_EPSILON_10000 ||
557 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
558 orientationAngle != ANGLE_180 ||
559 scale != Vector3(1.0f, 1.0f, 1.0f))
561 cleanDamagedRect = true;
567 cleanDamagedRect = true;
571 Rect<int32_t> viewportRect;
572 if(instruction.mIsViewportSet)
574 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
575 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
576 if(viewportRect.IsEmpty() || !viewportRect.IsValid())
578 cleanDamagedRect = true;
579 continue; // just skip funny use cases for now, empty viewport means it is set somewhere else
584 viewportRect = surfaceRect;
587 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
588 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
589 if(viewMatrix && projectionMatrix)
591 const RenderListContainer::SizeType count = instruction.RenderListCount();
592 for(RenderListContainer::SizeType index = 0u; index < count; ++index)
594 const RenderList* renderList = instruction.GetRenderList(index);
597 if(!renderList->IsEmpty())
599 const std::size_t listCount = renderList->Count();
600 for(uint32_t listIndex = 0u; listIndex < listCount; ++listIndex)
602 RenderItem& item = renderList->GetItem(listIndex);
603 // If the item does 3D transformation, make full update
604 if(item.mUpdateArea == Vector4::ZERO)
606 cleanDamagedRect = true;
608 // Save the full rect in the damaged list. We need it when this item is removed
609 DirtyRectKey dirtyRectKey(item.mNode, item.mRenderer);
610 auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
611 if(dirtyRectPos != itemsDirtyRects.end())
614 dirtyRectPos->second.visited = true;
615 dirtyRectPos->second.rect = surfaceRect;
619 // Else, just insert the new dirtyrect
620 itemsDirtyRects.insert({dirtyRectKey, surfaceRect});
626 DirtyRectKey dirtyRectKey(item.mNode, item.mRenderer);
627 // If the item refers to updated node or renderer.
628 if(item.mIsUpdated ||
630 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex)))))
632 item.mIsUpdated = false;
634 Vector4 updateArea = item.mRenderer ? item.mRenderer->GetVisualTransformedUpdateArea(mImpl->renderBufferIndex, item.mUpdateArea) : item.mUpdateArea;
636 rect = RenderItem::CalculateViewportSpaceAABB(item.mModelViewMatrix, Vector3(updateArea.x, updateArea.y, 0.0f), Vector3(updateArea.z, updateArea.w, 0.0f), viewportRect.width, viewportRect.height);
637 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
639 const int left = rect.x;
640 const int top = rect.y;
641 const int right = rect.x + rect.width;
642 const int bottom = rect.y + rect.height;
643 rect.x = (left / 16) * 16;
644 rect.y = (top / 16) * 16;
645 rect.width = ((right + 16) / 16) * 16 - rect.x;
646 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
648 // Found valid dirty rect.
649 auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
650 if(dirtyRectPos != itemsDirtyRects.end())
652 Rect<int> currentRect = rect;
654 // Same item, merge it with the previous rect
655 rect.Merge(dirtyRectPos->second.rect);
657 // Replace the rect as current
658 dirtyRectPos->second.visited = true;
659 dirtyRectPos->second.rect = currentRect;
663 // Else, just insert the new dirtyrect
664 itemsDirtyRects.insert({dirtyRectKey, rect});
667 damagedRects.push_back(rect);
672 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
673 // 2. Mark the related dirty rects as visited so they will not be removed below.
674 auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
675 if(dirtyRectPos != itemsDirtyRects.end())
677 dirtyRectPos->second.visited = true;
681 // The item is not in the list for some reason. Add it!
682 itemsDirtyRects.insert({dirtyRectKey, surfaceRect});
683 cleanDamagedRect = true; // And make full update at this frame
693 // Check removed nodes or removed renderers dirty rects
694 // Note, std::unordered_map end iterator is validate if we call erase.
695 for(auto iter = itemsDirtyRects.cbegin(), iterEnd = itemsDirtyRects.cend(); iter != iterEnd;)
697 if(!iter->second.visited)
699 damagedRects.push_back(iter->second.rect);
700 iter = itemsDirtyRects.erase(iter);
708 if(!cleanDamagedRect)
710 damagedRectCleaner.SetCleanOnReturn(false);
714 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
716 SceneGraph::Scene* sceneObject = GetImplementation(scene).GetSceneObject();
717 Rect<int> clippingRect = sceneObject->GetSurfaceRect();
719 RenderScene(status, scene, renderToFbo, clippingRect);
722 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
724 if(mImpl->partialUpdateAvailable == Integration::PartialUpdateAvailable::TRUE && !renderToFbo && clippingRect.IsEmpty())
726 // ClippingRect is empty. Skip rendering
730 // Reset main algorithms command buffer
731 mImpl->renderAlgorithms.ResetCommandBuffer();
733 auto mainCommandBuffer = mImpl->renderAlgorithms.GetMainCommandBuffer();
735 Internal::Scene& sceneInternal = GetImplementation(scene);
736 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
738 uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
740 std::vector<Graphics::RenderTarget*> targetstoPresent;
742 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
743 if(clippingRect == surfaceRect)
745 // Full rendering case
746 // Make clippingRect empty because we're doing full rendering now if the clippingRect is empty.
747 // To reduce side effects, keep this logic now.
748 clippingRect = Rect<int>();
751 // Prepare to lock and map standalone uniform buffer.
752 mImpl->uniformBufferManager->ReadyToLockUniformBuffer(mImpl->renderBufferIndex);
754 for(uint32_t i = 0; i < count; ++i)
756 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
758 if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
763 // Mark that we will require a post-render step to be performed (includes swap-buffers).
764 status.SetNeedsPostRender(true);
766 Rect<int32_t> viewportRect;
768 int32_t surfaceOrientation = sceneObject->GetSurfaceOrientation() + sceneObject->GetScreenOrientation();
769 if(surfaceOrientation >= 360)
771 surfaceOrientation -= 360;
774 // @todo Should these be part of scene?
775 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
776 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
778 Graphics::RenderTarget* currentRenderTarget = nullptr;
779 Graphics::RenderPass* currentRenderPass = nullptr;
780 std::vector<Graphics::ClearValue> currentClearValues{};
782 if(instruction.mFrameBuffer)
784 // Ensure graphics framebuffer is created, bind attachments and create render passes
785 // Only happens once per framebuffer. If the create fails, e.g. no attachments yet,
786 // then don't render to this framebuffer.
787 if(!instruction.mFrameBuffer->GetGraphicsObject())
789 const bool created = instruction.mFrameBuffer->CreateGraphicsObjects();
796 auto& clearValues = instruction.mFrameBuffer->GetGraphicsRenderPassClearValues();
798 // Set the clear color for first color attachment
799 if(instruction.mIsClearColorSet && !clearValues.empty())
801 clearValues[0].color = {
802 instruction.mClearColor.r,
803 instruction.mClearColor.g,
804 instruction.mClearColor.b,
805 instruction.mClearColor.a};
808 currentClearValues = clearValues;
810 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
813 currentRenderTarget = instruction.mFrameBuffer->GetGraphicsRenderTarget();
814 currentRenderPass = instruction.mFrameBuffer->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
816 else // no framebuffer
819 auto& clearValues = sceneObject->GetGraphicsRenderPassClearValues();
821 if(instruction.mIsClearColorSet)
823 clearValues[0].color = {
824 instruction.mClearColor.r,
825 instruction.mClearColor.g,
826 instruction.mClearColor.b,
827 instruction.mClearColor.a};
830 currentClearValues = clearValues;
832 // @todo SceneObject should already have the depth clear / stencil clear in the clearValues array.
833 // if the window has a depth/stencil buffer.
834 if((depthBufferAvailable == Integration::DepthBufferAvailable::TRUE ||
835 stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE) &&
836 (currentClearValues.size() <= 1))
838 currentClearValues.emplace_back();
839 currentClearValues.back().depthStencil.depth = 0;
840 currentClearValues.back().depthStencil.stencil = 0;
843 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
845 currentRenderTarget = sceneObject->GetSurfaceRenderTarget();
846 currentRenderPass = sceneObject->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
849 targetstoPresent.emplace_back(currentRenderTarget);
851 // reset the program matrices for all programs once per frame
852 // this ensures we will set view and projection matrix once per program per camera
853 mImpl->programController.ResetProgramMatrices();
855 if(instruction.mFrameBuffer)
857 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
858 for(unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
860 mImpl->textureDependencyList.PushBack(instruction.mFrameBuffer->GetTexture(i0));
864 if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
866 // Offscreen buffer rendering
867 if(instruction.mIsViewportSet)
869 // For Viewport the lower-left corner is (0,0)
870 const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
871 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
875 viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
877 surfaceOrientation = 0;
879 else // No Offscreen frame buffer rendering
881 // Check whether a viewport is specified, otherwise the full surface size is used
882 if(instruction.mIsViewportSet)
884 // For Viewport the lower-left corner is (0,0)
885 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
886 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
890 viewportRect = surfaceRect;
894 // Set surface orientation
895 // @todo Inform graphics impl by another route.
896 // was: mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
898 /*** Clear region of framebuffer or surface before drawing ***/
899 bool clearFullFrameRect = (surfaceRect == viewportRect);
900 if(instruction.mFrameBuffer != nullptr)
902 Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
903 clearFullFrameRect = (frameRect == viewportRect);
906 if(!clippingRect.IsEmpty())
908 if(!clippingRect.Intersect(viewportRect))
910 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
911 clippingRect = Rect<int>();
913 clearFullFrameRect = false;
916 Graphics::Rect2D scissorArea{viewportRect.x, viewportRect.y, uint32_t(viewportRect.width), uint32_t(viewportRect.height)};
917 if(instruction.mIsClearColorSet)
919 if(!clearFullFrameRect)
921 if(!clippingRect.IsEmpty())
923 scissorArea = {clippingRect.x, clippingRect.y, uint32_t(clippingRect.width), uint32_t(clippingRect.height)};
928 // Scissor's value should be set based on the default system coordinates.
929 // When the surface is rotated, the input values already were set with the rotated angle.
930 // So, re-calculation is needed.
931 scissorArea = RecalculateScissorArea(scissorArea, surfaceOrientation, surfaceRect);
934 mainCommandBuffer->BeginRenderPass(
940 mainCommandBuffer->SetViewport({float(viewportRect.x),
941 float(viewportRect.y),
942 float(viewportRect.width),
943 float(viewportRect.height)});
945 // Clear the list of bound textures
946 mImpl->boundTextures.Clear();
948 mImpl->renderAlgorithms.ProcessRenderInstruction(
950 mImpl->renderBufferIndex,
951 depthBufferAvailable,
952 stencilBufferAvailable,
953 mImpl->boundTextures,
957 Uint16Pair(surfaceRect.width, surfaceRect.height));
959 Graphics::SyncObject* syncObject{nullptr};
960 // If the render instruction has an associated render tracker (owned separately)
961 // and framebuffer, create a one shot sync object, and use it to determine when
962 // the render pass has finished executing on GPU.
963 if(instruction.mRenderTracker && instruction.mFrameBuffer)
965 syncObject = instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController);
966 instruction.mRenderTracker = nullptr;
968 mainCommandBuffer->EndRenderPass(syncObject);
971 // Unlock standalone uniform buffer.
972 mImpl->uniformBufferManager->UnlockUniformBuffer(mImpl->renderBufferIndex);
974 mImpl->renderAlgorithms.SubmitCommandBuffer();
975 mImpl->commandBufferSubmitted = true;
977 std::sort(targetstoPresent.begin(), targetstoPresent.end());
979 Graphics::RenderTarget* rt = nullptr;
980 for(auto& target : targetstoPresent)
984 mImpl->graphicsController.PresentRenderTarget(target);
990 void RenderManager::PostRender()
992 if(!mImpl->commandBufferSubmitted)
994 // Rendering is skipped but there may be pending tasks. Flush them.
995 Graphics::SubmitInfo submitInfo;
996 submitInfo.cmdBuffer.clear(); // Only flush
997 submitInfo.flags = 0 | Graphics::SubmitFlagBits::FLUSH;
998 mImpl->graphicsController.SubmitCommandBuffers(submitInfo);
1000 mImpl->commandBufferSubmitted = true;
1003 // Notify RenderGeometries that rendering has finished
1004 for(auto&& iter : mImpl->geometryContainer)
1006 iter->OnRenderFinished();
1009 // Notify RenderTexture that rendering has finished
1010 for(auto&& iter : mImpl->textureContainer)
1012 iter->OnRenderFinished();
1015 mImpl->UpdateTrackers();
1017 uint32_t count = 0u;
1018 for(auto& scene : mImpl->sceneContainer)
1020 count += scene->GetRenderInstructions().Count(mImpl->renderBufferIndex);
1023 const bool haveInstructions = count > 0u;
1025 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1026 mImpl->lastFrameWasRendered = haveInstructions;
1029 * The rendering has finished; swap to the next buffer.
1030 * Ideally the update has just finished using this buffer; otherwise the render thread
1031 * should block until the update has finished.
1033 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1035 DALI_PRINT_RENDER_END();
1038 } // namespace SceneGraph
1040 } // namespace Internal