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;
100 * @brief The number of dirty rects per renderer in itemDirtyRects list.
101 * If this value is 3, keep only last 3 dirty rects for the same node and renderer.
103 constexpr int MAX_DIRTY_RECT_PER_RENDERER = 3;
106 * Structure to contain internal data
108 struct RenderManager::Impl
110 Impl(Graphics::Controller& graphicsController,
111 Integration::DepthBufferAvailable depthBufferAvailableParam,
112 Integration::StencilBufferAvailable stencilBufferAvailableParam,
113 Integration::PartialUpdateAvailable partialUpdateAvailableParam)
114 : graphicsController(graphicsController),
116 renderAlgorithms(graphicsController),
118 renderBufferIndex(SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX),
122 frameBufferContainer(),
123 lastFrameWasRendered(false),
124 programController(graphicsController),
125 shaderCache(graphicsController),
126 depthBufferAvailable(depthBufferAvailableParam),
127 stencilBufferAvailable(stencilBufferAvailableParam),
128 partialUpdateAvailable(partialUpdateAvailableParam)
130 // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
131 threadPool = std::make_unique<Dali::ThreadPool>();
132 threadPool->Initialize(1u);
134 uniformBufferManager = std::make_unique<Render::UniformBufferManager>(&graphicsController);
135 pipelineCache = std::make_unique<Render::PipelineCache>(graphicsController);
140 threadPool.reset(nullptr); // reset now to maintain correct destruction order
143 void AddRenderTracker(Render::RenderTracker* renderTracker)
145 DALI_ASSERT_DEBUG(renderTracker != nullptr);
146 mRenderTrackers.PushBack(renderTracker);
149 void RemoveRenderTracker(Render::RenderTracker* renderTracker)
151 mRenderTrackers.EraseObject(renderTracker);
154 void UpdateTrackers()
156 for(auto&& iter : mRenderTrackers)
158 iter->PollSyncObject();
162 // the order is important for destruction,
163 Graphics::Controller& graphicsController;
164 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
166 std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
168 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
170 uint32_t frameCount; ///< The current frame count
171 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
173 OwnerContainer<Render::Renderer*> rendererContainer; ///< List of owned renderers
174 OwnerContainer<Render::Sampler*> samplerContainer; ///< List of owned samplers
175 OwnerContainer<Render::Texture*> textureContainer; ///< List of owned textures
176 OwnerContainer<Render::FrameBuffer*> frameBufferContainer; ///< List of owned framebuffers
177 OwnerContainer<Render::VertexBuffer*> vertexBufferContainer; ///< List of owned vertex buffers
178 OwnerContainer<Render::Geometry*> geometryContainer; ///< List of owned Geometries
180 bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
182 OwnerContainer<Render::RenderTracker*> mRenderTrackers; ///< List of render trackers
184 ProgramController programController; ///< Owner of the programs
185 Render::ShaderCache shaderCache; ///< The cache for the graphics shaders
187 std::unique_ptr<Render::UniformBufferManager> uniformBufferManager; ///< The uniform buffer manager
188 std::unique_ptr<Render::PipelineCache> pipelineCache;
190 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
191 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
192 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
194 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
195 Vector<Graphics::Texture*> boundTextures; ///< The textures bound for rendering
196 Vector<Graphics::Texture*> textureDependencyList; ///< The dependency list of bound textures
199 RenderManager* RenderManager::New(Graphics::Controller& graphicsController,
200 Integration::DepthBufferAvailable depthBufferAvailable,
201 Integration::StencilBufferAvailable stencilBufferAvailable,
202 Integration::PartialUpdateAvailable partialUpdateAvailable)
204 auto* manager = new RenderManager;
205 manager->mImpl = new Impl(graphicsController,
206 depthBufferAvailable,
207 stencilBufferAvailable,
208 partialUpdateAvailable);
212 RenderManager::RenderManager()
217 RenderManager::~RenderManager()
222 RenderQueue& RenderManager::GetRenderQueue()
224 return mImpl->renderQueue;
227 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
231 void RenderManager::AddRenderer(OwnerPointer<Render::Renderer>& renderer)
233 // Initialize the renderer as we are now in render thread
234 renderer->Initialize(mImpl->graphicsController, mImpl->programController, mImpl->shaderCache, *(mImpl->uniformBufferManager.get()), *(mImpl->pipelineCache.get()));
236 mImpl->rendererContainer.PushBack(renderer.Release());
239 void RenderManager::RemoveRenderer(Render::Renderer* renderer)
241 mImpl->rendererContainer.EraseObject(renderer);
244 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
246 sampler->Initialize(mImpl->graphicsController);
247 mImpl->samplerContainer.PushBack(sampler.Release());
250 void RenderManager::RemoveSampler(Render::Sampler* sampler)
252 mImpl->samplerContainer.EraseObject(sampler);
255 void RenderManager::AddTexture(OwnerPointer<Render::Texture>& texture)
257 texture->Initialize(mImpl->graphicsController);
258 mImpl->textureContainer.PushBack(texture.Release());
261 void RenderManager::RemoveTexture(Render::Texture* texture)
263 DALI_ASSERT_DEBUG(NULL != texture);
265 // Find the texture, use std::find so we can do the erase safely
266 auto iter = std::find(mImpl->textureContainer.begin(), mImpl->textureContainer.end(), texture);
268 if(iter != mImpl->textureContainer.end())
271 mImpl->textureContainer.Erase(iter); // Texture found; now destroy it
275 void RenderManager::UploadTexture(Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params)
277 texture->Upload(pixelData, params);
280 void RenderManager::GenerateMipmaps(Render::Texture* texture)
282 texture->GenerateMipmaps();
285 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
287 sampler->SetFilterMode(static_cast<Dali::FilterMode::Type>(minFilterMode),
288 static_cast<Dali::FilterMode::Type>(magFilterMode));
291 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
293 sampler->SetWrapMode(static_cast<Dali::WrapMode::Type>(rWrapMode),
294 static_cast<Dali::WrapMode::Type>(sWrapMode),
295 static_cast<Dali::WrapMode::Type>(tWrapMode));
298 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
300 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
301 mImpl->frameBufferContainer.PushBack(frameBufferPtr);
302 frameBufferPtr->Initialize(mImpl->graphicsController);
305 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
307 DALI_ASSERT_DEBUG(nullptr != frameBuffer);
309 // Find the framebuffer, use std:find so we can safely do the erase
310 auto iter = std::find(mImpl->frameBufferContainer.begin(), mImpl->frameBufferContainer.end(), frameBuffer);
312 if(iter != mImpl->frameBufferContainer.end())
314 frameBuffer->Destroy();
315 mImpl->frameBufferContainer.Erase(iter); // frameBuffer found; now destroy it
319 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
321 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
322 mImpl->sceneContainer.push_back(scene);
325 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
327 auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
328 if(iter != mImpl->sceneContainer.end())
330 mImpl->sceneContainer.erase(iter);
334 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
336 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
339 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
341 frameBuffer->AttachColorTexture(texture, mipmapLevel, layer);
344 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
346 frameBuffer->AttachDepthTexture(texture, mipmapLevel);
349 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
351 frameBuffer->AttachDepthStencilTexture(texture, mipmapLevel);
354 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
356 mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
359 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
361 mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
364 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
366 vertexBuffer->SetFormat(format.Release());
369 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
371 vertexBuffer->SetData(data.Release(), size);
374 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Dali::Vector<uint16_t>& indices)
376 geometry->SetIndexBuffer(indices);
379 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
381 mImpl->geometryContainer.PushBack(geometry.Release());
384 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
386 auto iter = std::find(mImpl->geometryContainer.begin(), mImpl->geometryContainer.end(), geometry);
388 if(iter != mImpl->geometryContainer.end())
390 mImpl->geometryContainer.Erase(iter);
394 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
396 DALI_ASSERT_DEBUG(nullptr != geometry);
399 for(auto&& iter : mImpl->geometryContainer)
403 iter->AddVertexBuffer(vertexBuffer);
409 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
411 DALI_ASSERT_DEBUG(nullptr != geometry);
414 for(auto&& iter : mImpl->geometryContainer)
418 iter->RemoveVertexBuffer(vertexBuffer);
424 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
426 geometry->SetType(Render::Geometry::Type(geometryType));
429 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
431 mImpl->AddRenderTracker(renderTracker);
434 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
436 mImpl->RemoveRenderTracker(renderTracker);
439 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear)
441 DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
444 mImpl->uniformBufferManager->GetUniformBufferViewPool(mImpl->renderBufferIndex)->Rollback();
446 // Increment the frame count at the beginning of each frame
449 // Process messages queued during previous update
450 mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
453 for(auto& i : mImpl->sceneContainer)
455 count += i->GetRenderInstructions().Count(mImpl->renderBufferIndex);
458 const bool haveInstructions = count > 0u;
460 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");
462 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
463 if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
465 DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
467 // Upload the geometries
468 for(auto&& geom : mImpl->geometryContainer)
470 geom->Upload(mImpl->graphicsController);
475 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
477 if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
482 Internal::Scene& sceneInternal = GetImplementation(scene);
483 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
485 if(sceneObject->IsRenderingSkipped())
487 // We don't need to calculate dirty rects
491 class DamagedRectsCleaner
494 explicit DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects, Rect<int>& surfaceRect)
495 : mDamagedRects(damagedRects),
496 mSurfaceRect(surfaceRect),
501 void SetCleanOnReturn(bool cleanOnReturn)
503 mCleanOnReturn = cleanOnReturn;
506 ~DamagedRectsCleaner()
510 mDamagedRects.clear();
511 mDamagedRects.push_back(mSurfaceRect);
516 std::vector<Rect<int>>& mDamagedRects;
517 Rect<int> mSurfaceRect;
521 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
523 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
524 DamagedRectsCleaner damagedRectCleaner(damagedRects, surfaceRect);
526 // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
527 // so you don't need to sort: std::stable_sort(itemsDirtyRects.begin(), itemsDirtyRects.end());
528 std::vector<DirtyRect>& itemsDirtyRects = sceneObject->GetItemsDirtyRects();
529 for(DirtyRect& dirtyRect : itemsDirtyRects)
531 dirtyRect.visited = false;
534 uint32_t instructionCount = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
535 for(uint32_t i = 0; i < instructionCount; ++i)
537 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
539 if(instruction.mFrameBuffer)
541 return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
544 const Camera* camera = instruction.GetCamera();
545 if(camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
547 const Node* node = instruction.GetCamera()->GetNode();
552 Quaternion orientation;
553 node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
555 Vector3 orientationAxis;
556 Radian orientationAngle;
557 orientation.ToAxisAngle(orientationAxis, orientationAngle);
559 if(position.x > Math::MACHINE_EPSILON_10000 ||
560 position.y > Math::MACHINE_EPSILON_10000 ||
561 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
562 orientationAngle != ANGLE_180 ||
563 scale != Vector3(1.0f, 1.0f, 1.0f))
574 Rect<int32_t> viewportRect;
575 if(instruction.mIsViewportSet)
577 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
578 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
579 if(viewportRect.IsEmpty() || !viewportRect.IsValid())
581 return; // just skip funny use cases for now, empty viewport means it is set somewhere else
586 viewportRect = surfaceRect;
589 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
590 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
591 if(viewMatrix && projectionMatrix)
593 const RenderListContainer::SizeType count = instruction.RenderListCount();
594 for(RenderListContainer::SizeType index = 0u; index < count; ++index)
596 const RenderList* renderList = instruction.GetRenderList(index);
599 if(!renderList->IsEmpty())
601 const std::size_t listCount = renderList->Count();
602 for(uint32_t listIndex = 0u; listIndex < listCount; ++listIndex)
604 RenderItem& item = renderList->GetItem(listIndex);
605 // If the item does 3D transformation, do early exit and clean the damaged rect array
606 if(item.mUpdateSize == Vector3::ZERO)
612 DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
613 // If the item refers to updated node or renderer.
614 if(item.mIsUpdated ||
616 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
618 item.mIsUpdated = false;
620 rect = RenderItem::CalculateViewportSpaceAABB(item.mModelViewMatrix, item.mUpdateSize, viewportRect.width, viewportRect.height);
621 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
623 const int left = rect.x;
624 const int top = rect.y;
625 const int right = rect.x + rect.width;
626 const int bottom = rect.y + rect.height;
627 rect.x = (left / 16) * 16;
628 rect.y = (top / 16) * 16;
629 rect.width = ((right + 16) / 16) * 16 - rect.x;
630 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
632 // Found valid dirty rect.
633 // 1. Mark the related dirty rects as visited so they will not be removed below.
634 // 2. Keep only last "MAX_DIRTY_RECT_PER_RENDERER" dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
635 // 3-1. If itemDirtyRect hold MAX_DIRTY_RECT_PER_RENDERER rects, remove oldest one and insert it in the sorted array of the dirty rects.
636 // 3-2. Else, Insert it in the sorted array of the dirty rects.
637 dirtyRect.rect = rect;
638 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
640 auto originDirtyRectPos = dirtyRectPos;
641 bool hasMaxDirtyRect = false;
642 while(dirtyRectPos != itemsDirtyRects.end())
644 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
649 dirtyRectPos->visited = true;
650 rect.Merge(dirtyRectPos->rect);
654 if((dirtyRectPos - originDirtyRectPos) == MAX_DIRTY_RECT_PER_RENDERER) // no more than MAX_DIRTY_RECT_PER_RENDERER previous rects
656 hasMaxDirtyRect = true;
663 // If we have already MAX_DIRTY_RECT_PER_RENDERER for the same item, just copy it.
664 // Remove the oldest rect (at pos + MAX_DIRTY_RECT_PER_RENDERER - 1)
665 // and move other rects one step.
666 // and insert new dirtyRect at originDirtyRectPos.
667 auto pos = originDirtyRectPos - itemsDirtyRects.begin();
668 for(auto i = MAX_DIRTY_RECT_PER_RENDERER - 1; i > 0; i--)
670 itemsDirtyRects[pos + i] = itemsDirtyRects[pos + i - 1];
672 itemsDirtyRects[pos] = dirtyRect;
676 // Else, just insert the new dirtyrect in the correct position
677 itemsDirtyRects.insert(originDirtyRectPos, dirtyRect);
680 damagedRects.push_back(rect);
685 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
686 // 2. Mark the related dirty rects as visited so they will not be removed below.
687 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
688 while(dirtyRectPos != itemsDirtyRects.end())
690 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
695 dirtyRectPos->visited = true;
706 // Check removed nodes or removed renderers dirty rects
707 auto i = itemsDirtyRects.begin();
708 auto j = itemsDirtyRects.begin();
709 while(i != itemsDirtyRects.end())
717 Rect<int>& dirtRect = i->rect;
718 damagedRects.push_back(dirtRect);
723 itemsDirtyRects.resize(j - itemsDirtyRects.begin());
724 damagedRectCleaner.SetCleanOnReturn(false);
726 // Reset updated flag from the root
727 Layer* root = sceneObject->GetRoot();
730 root->SetUpdatedTree(false);
734 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
736 SceneGraph::Scene* sceneObject = GetImplementation(scene).GetSceneObject();
737 Rect<int> clippingRect = sceneObject->GetSurfaceRect();
739 RenderScene(status, scene, renderToFbo, clippingRect);
742 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
744 if(mImpl->partialUpdateAvailable == Integration::PartialUpdateAvailable::TRUE && !renderToFbo && clippingRect.IsEmpty())
746 // ClippingRect is empty. Skip rendering
750 // Reset main algorithms command buffer
751 mImpl->renderAlgorithms.ResetCommandBuffer();
753 auto mainCommandBuffer = mImpl->renderAlgorithms.GetMainCommandBuffer();
755 Internal::Scene& sceneInternal = GetImplementation(scene);
756 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
758 uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
760 std::vector<Graphics::RenderTarget*> targetstoPresent;
762 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
763 if(clippingRect == surfaceRect)
765 // Full rendering case
766 // Make clippingRect empty because we're doing full rendering now if the clippingRect is empty.
767 // To reduce side effects, keep this logic now.
768 clippingRect = Rect<int>();
771 for(uint32_t i = 0; i < count; ++i)
773 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
775 if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
780 // Mark that we will require a post-render step to be performed (includes swap-buffers).
781 status.SetNeedsPostRender(true);
783 Rect<int32_t> viewportRect;
785 int32_t surfaceOrientation = sceneObject->GetSurfaceOrientation();
787 // @todo Should these be part of scene?
788 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
789 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
791 Graphics::RenderTarget* currentRenderTarget = nullptr;
792 Graphics::RenderPass* currentRenderPass = nullptr;
793 std::vector<Graphics::ClearValue> currentClearValues{};
795 if(instruction.mFrameBuffer)
797 // Ensure graphics framebuffer is created, bind attachments and create render passes
798 // Only happens once per framebuffer. If the create fails, e.g. no attachments yet,
799 // then don't render to this framebuffer.
800 if(!instruction.mFrameBuffer->GetGraphicsObject())
802 const bool created = instruction.mFrameBuffer->CreateGraphicsObjects();
809 auto& clearValues = instruction.mFrameBuffer->GetGraphicsRenderPassClearValues();
811 // Set the clear color for first color attachment
812 if(instruction.mIsClearColorSet && !clearValues.empty())
814 clearValues[0].color = {
815 instruction.mClearColor.r,
816 instruction.mClearColor.g,
817 instruction.mClearColor.b,
818 instruction.mClearColor.a};
821 currentClearValues = clearValues;
823 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
826 currentRenderTarget = instruction.mFrameBuffer->GetGraphicsRenderTarget();
827 currentRenderPass = instruction.mFrameBuffer->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
829 else // no framebuffer
832 auto& clearValues = sceneObject->GetGraphicsRenderPassClearValues();
834 if(instruction.mIsClearColorSet)
836 clearValues[0].color = {
837 instruction.mClearColor.r,
838 instruction.mClearColor.g,
839 instruction.mClearColor.b,
840 instruction.mClearColor.a};
843 currentClearValues = clearValues;
845 // @todo SceneObject should already have the depth clear / stencil clear in the clearValues array.
846 // if the window has a depth/stencil buffer.
847 if((depthBufferAvailable == Integration::DepthBufferAvailable::TRUE ||
848 stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE) &&
849 (currentClearValues.size() <= 1))
851 currentClearValues.emplace_back();
852 currentClearValues.back().depthStencil.depth = 0;
853 currentClearValues.back().depthStencil.stencil = 0;
856 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
858 currentRenderTarget = sceneObject->GetSurfaceRenderTarget();
859 currentRenderPass = sceneObject->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
862 targetstoPresent.emplace_back(currentRenderTarget);
864 // reset the program matrices for all programs once per frame
865 // this ensures we will set view and projection matrix once per program per camera
866 mImpl->programController.ResetProgramMatrices();
868 if(instruction.mFrameBuffer)
870 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
871 for(unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
873 mImpl->textureDependencyList.PushBack(instruction.mFrameBuffer->GetTexture(i0));
877 if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
879 // Offscreen buffer rendering
880 if(instruction.mIsViewportSet)
882 // For Viewport the lower-left corner is (0,0)
883 const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
884 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
888 viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
890 surfaceOrientation = 0;
892 else // No Offscreen frame buffer rendering
894 // Check whether a viewport is specified, otherwise the full surface size is used
895 if(instruction.mIsViewportSet)
897 // For Viewport the lower-left corner is (0,0)
898 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
899 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
903 viewportRect = surfaceRect;
907 // Set surface orientation
908 // @todo Inform graphics impl by another route.
909 // was: mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
911 /*** Clear region of framebuffer or surface before drawing ***/
912 bool clearFullFrameRect = (surfaceRect == viewportRect);
913 if(instruction.mFrameBuffer != nullptr)
915 Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
916 clearFullFrameRect = (frameRect == viewportRect);
919 if(!clippingRect.IsEmpty())
921 if(!clippingRect.Intersect(viewportRect))
923 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
924 clippingRect = Rect<int>();
926 clearFullFrameRect = false;
929 Graphics::Rect2D scissorArea{viewportRect.x, viewportRect.y, uint32_t(viewportRect.width), uint32_t(viewportRect.height)};
930 if(instruction.mIsClearColorSet)
932 if(!clearFullFrameRect)
934 if(!clippingRect.IsEmpty())
936 scissorArea = {clippingRect.x, clippingRect.y, uint32_t(clippingRect.width), uint32_t(clippingRect.height)};
941 // Scissor's value should be set based on the default system coordinates.
942 // When the surface is rotated, the input values already were set with the rotated angle.
943 // So, re-calculation is needed.
944 scissorArea = RecalculateScissorArea(scissorArea, surfaceOrientation, viewportRect);
947 mainCommandBuffer->BeginRenderPass(
953 mainCommandBuffer->SetViewport({float(viewportRect.x),
954 float(viewportRect.y),
955 float(viewportRect.width),
956 float(viewportRect.height)});
958 // Clear the list of bound textures
959 mImpl->boundTextures.Clear();
961 mImpl->renderAlgorithms.ProcessRenderInstruction(
963 mImpl->renderBufferIndex,
964 depthBufferAvailable,
965 stencilBufferAvailable,
966 mImpl->boundTextures,
971 Graphics::SyncObject* syncObject{nullptr};
972 // If the render instruction has an associated render tracker (owned separately)
973 // and framebuffer, create a one shot sync object, and use it to determine when
974 // the render pass has finished executing on GPU.
975 if(instruction.mRenderTracker && instruction.mFrameBuffer)
977 syncObject = instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController);
978 instruction.mRenderTracker = nullptr;
980 mainCommandBuffer->EndRenderPass(syncObject);
982 mImpl->renderAlgorithms.SubmitCommandBuffer();
984 std::sort(targetstoPresent.begin(), targetstoPresent.end());
986 Graphics::RenderTarget* rt = nullptr;
987 for(auto& target : targetstoPresent)
991 mImpl->graphicsController.PresentRenderTarget(target);
997 void RenderManager::PostRender()
999 // Notify RenderGeometries that rendering has finished
1000 for(auto&& iter : mImpl->geometryContainer)
1002 iter->OnRenderFinished();
1005 mImpl->UpdateTrackers();
1007 uint32_t count = 0u;
1008 for(auto& scene : mImpl->sceneContainer)
1010 count += scene->GetRenderInstructions().Count(mImpl->renderBufferIndex);
1013 const bool haveInstructions = count > 0u;
1015 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1016 mImpl->lastFrameWasRendered = haveInstructions;
1019 * The rendering has finished; swap to the next buffer.
1020 * Ideally the update has just finished using this buffer; otherwise the render thread
1021 * should block until the update has finished.
1023 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1025 DALI_PRINT_RENDER_END();
1028 } // namespace SceneGraph
1030 } // namespace Internal