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 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 cleanDamagedRect = true;
541 continue; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
544 const Camera* camera = instruction.GetCamera();
545 if(camera && camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
549 Quaternion orientation;
550 camera->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
552 Vector3 orientationAxis;
553 Radian orientationAngle;
554 orientation.ToAxisAngle(orientationAxis, orientationAngle);
556 if(position.x > Math::MACHINE_EPSILON_10000 ||
557 position.y > Math::MACHINE_EPSILON_10000 ||
558 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
559 orientationAngle != ANGLE_180 ||
560 scale != Vector3(1.0f, 1.0f, 1.0f))
562 cleanDamagedRect = true;
568 cleanDamagedRect = true;
572 Rect<int32_t> viewportRect;
573 if(instruction.mIsViewportSet)
575 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
576 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
577 if(viewportRect.IsEmpty() || !viewportRect.IsValid())
579 cleanDamagedRect = true;
580 continue; // 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, make full update
605 if(item.mUpdateArea == Vector4::ZERO)
607 cleanDamagedRect = true;
609 // Save the full rect in the damaged list. We need it when this item is removed
610 DirtyRect dirtyRect(item.mNode, item.mRenderer, surfaceRect);
611 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
612 if(dirtyRectPos != itemsDirtyRects.end() && dirtyRectPos->node == item.mNode && dirtyRectPos->renderer == item.mRenderer)
615 dirtyRectPos->visited = true;
616 dirtyRectPos->rect = dirtyRect.rect;
620 // Else, just insert the new dirtyrect in the correct position
621 itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
627 DirtyRect dirtyRect(item.mNode, item.mRenderer, rect);
628 // If the item refers to updated node or renderer.
629 if(item.mIsUpdated ||
631 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex)))))
633 item.mIsUpdated = false;
635 Vector4 updateArea = item.mRenderer ? item.mRenderer->GetVisualTransformedUpdateArea(mImpl->renderBufferIndex, item.mUpdateArea) : item.mUpdateArea;
637 rect = RenderItem::CalculateViewportSpaceAABB(item.mModelViewMatrix, Vector3(updateArea.x, updateArea.y, 0.0f), Vector3(updateArea.z, updateArea.w, 0.0f), viewportRect.width, viewportRect.height);
638 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
640 const int left = rect.x;
641 const int top = rect.y;
642 const int right = rect.x + rect.width;
643 const int bottom = rect.y + rect.height;
644 rect.x = (left / 16) * 16;
645 rect.y = (top / 16) * 16;
646 rect.width = ((right + 16) / 16) * 16 - rect.x;
647 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
649 // Found valid dirty rect.
650 dirtyRect.rect = rect;
651 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
653 if(dirtyRectPos != itemsDirtyRects.end() && dirtyRectPos->node == item.mNode && dirtyRectPos->renderer == item.mRenderer)
655 // Same item, merge it with the previous rect
656 rect.Merge(dirtyRectPos->rect);
659 dirtyRectPos->visited = true;
660 dirtyRectPos->rect = dirtyRect.rect;
664 // Else, just insert the new dirtyrect in the correct position
665 itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
668 damagedRects.push_back(rect);
673 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
674 // 2. Mark the related dirty rects as visited so they will not be removed below.
675 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
676 if(dirtyRectPos != itemsDirtyRects.end() && dirtyRectPos->node == item.mNode && dirtyRectPos->renderer == item.mRenderer)
678 dirtyRectPos->visited = true;
682 // The item is not in the list for some reason. Add it!
683 dirtyRect.rect = surfaceRect;
684 itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
685 cleanDamagedRect = true; // And make full update at this frame
695 // Check removed nodes or removed renderers dirty rects
696 auto i = itemsDirtyRects.begin();
697 auto j = itemsDirtyRects.begin();
698 while(i != itemsDirtyRects.end())
706 Rect<int>& dirtRect = i->rect;
707 damagedRects.push_back(dirtRect);
712 itemsDirtyRects.resize(j - itemsDirtyRects.begin());
714 if(!cleanDamagedRect)
716 damagedRectCleaner.SetCleanOnReturn(false);
720 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
722 SceneGraph::Scene* sceneObject = GetImplementation(scene).GetSceneObject();
723 Rect<int> clippingRect = sceneObject->GetSurfaceRect();
725 RenderScene(status, scene, renderToFbo, clippingRect);
728 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
730 if(mImpl->partialUpdateAvailable == Integration::PartialUpdateAvailable::TRUE && !renderToFbo && clippingRect.IsEmpty())
732 // ClippingRect is empty. Skip rendering
736 // Reset main algorithms command buffer
737 mImpl->renderAlgorithms.ResetCommandBuffer();
739 auto mainCommandBuffer = mImpl->renderAlgorithms.GetMainCommandBuffer();
741 Internal::Scene& sceneInternal = GetImplementation(scene);
742 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
744 uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
746 std::vector<Graphics::RenderTarget*> targetstoPresent;
748 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
749 if(clippingRect == surfaceRect)
751 // Full rendering case
752 // Make clippingRect empty because we're doing full rendering now if the clippingRect is empty.
753 // To reduce side effects, keep this logic now.
754 clippingRect = Rect<int>();
757 // Prepare to lock and map standalone uniform buffer.
758 mImpl->uniformBufferManager->ReadyToLockUniformBuffer(mImpl->renderBufferIndex);
760 for(uint32_t i = 0; i < count; ++i)
762 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
764 if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
769 // Mark that we will require a post-render step to be performed (includes swap-buffers).
770 status.SetNeedsPostRender(true);
772 Rect<int32_t> viewportRect;
774 int32_t surfaceOrientation = sceneObject->GetSurfaceOrientation() + sceneObject->GetScreenOrientation();
775 if(surfaceOrientation >= 360)
777 surfaceOrientation -= 360;
780 // @todo Should these be part of scene?
781 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
782 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
784 Graphics::RenderTarget* currentRenderTarget = nullptr;
785 Graphics::RenderPass* currentRenderPass = nullptr;
786 std::vector<Graphics::ClearValue> currentClearValues{};
788 if(instruction.mFrameBuffer)
790 // Ensure graphics framebuffer is created, bind attachments and create render passes
791 // Only happens once per framebuffer. If the create fails, e.g. no attachments yet,
792 // then don't render to this framebuffer.
793 if(!instruction.mFrameBuffer->GetGraphicsObject())
795 const bool created = instruction.mFrameBuffer->CreateGraphicsObjects();
802 auto& clearValues = instruction.mFrameBuffer->GetGraphicsRenderPassClearValues();
804 // Set the clear color for first color attachment
805 if(instruction.mIsClearColorSet && !clearValues.empty())
807 clearValues[0].color = {
808 instruction.mClearColor.r,
809 instruction.mClearColor.g,
810 instruction.mClearColor.b,
811 instruction.mClearColor.a};
814 currentClearValues = clearValues;
816 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
819 currentRenderTarget = instruction.mFrameBuffer->GetGraphicsRenderTarget();
820 currentRenderPass = instruction.mFrameBuffer->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
822 else // no framebuffer
825 auto& clearValues = sceneObject->GetGraphicsRenderPassClearValues();
827 if(instruction.mIsClearColorSet)
829 clearValues[0].color = {
830 instruction.mClearColor.r,
831 instruction.mClearColor.g,
832 instruction.mClearColor.b,
833 instruction.mClearColor.a};
836 currentClearValues = clearValues;
838 // @todo SceneObject should already have the depth clear / stencil clear in the clearValues array.
839 // if the window has a depth/stencil buffer.
840 if((depthBufferAvailable == Integration::DepthBufferAvailable::TRUE ||
841 stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE) &&
842 (currentClearValues.size() <= 1))
844 currentClearValues.emplace_back();
845 currentClearValues.back().depthStencil.depth = 0;
846 currentClearValues.back().depthStencil.stencil = 0;
849 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
851 currentRenderTarget = sceneObject->GetSurfaceRenderTarget();
852 currentRenderPass = sceneObject->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
855 targetstoPresent.emplace_back(currentRenderTarget);
857 // reset the program matrices for all programs once per frame
858 // this ensures we will set view and projection matrix once per program per camera
859 mImpl->programController.ResetProgramMatrices();
861 if(instruction.mFrameBuffer)
863 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
864 for(unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
866 mImpl->textureDependencyList.PushBack(instruction.mFrameBuffer->GetTexture(i0));
870 if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
872 // Offscreen buffer rendering
873 if(instruction.mIsViewportSet)
875 // For Viewport the lower-left corner is (0,0)
876 const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
877 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
881 viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
883 surfaceOrientation = 0;
885 else // No Offscreen frame buffer rendering
887 // Check whether a viewport is specified, otherwise the full surface size is used
888 if(instruction.mIsViewportSet)
890 // For Viewport the lower-left corner is (0,0)
891 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
892 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
896 viewportRect = surfaceRect;
900 // Set surface orientation
901 // @todo Inform graphics impl by another route.
902 // was: mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
904 /*** Clear region of framebuffer or surface before drawing ***/
905 bool clearFullFrameRect = (surfaceRect == viewportRect);
906 if(instruction.mFrameBuffer != nullptr)
908 Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
909 clearFullFrameRect = (frameRect == viewportRect);
912 if(!clippingRect.IsEmpty())
914 if(!clippingRect.Intersect(viewportRect))
916 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
917 clippingRect = Rect<int>();
919 clearFullFrameRect = false;
922 Graphics::Rect2D scissorArea{viewportRect.x, viewportRect.y, uint32_t(viewportRect.width), uint32_t(viewportRect.height)};
923 if(instruction.mIsClearColorSet)
925 if(!clearFullFrameRect)
927 if(!clippingRect.IsEmpty())
929 scissorArea = {clippingRect.x, clippingRect.y, uint32_t(clippingRect.width), uint32_t(clippingRect.height)};
934 // Scissor's value should be set based on the default system coordinates.
935 // When the surface is rotated, the input values already were set with the rotated angle.
936 // So, re-calculation is needed.
937 scissorArea = RecalculateScissorArea(scissorArea, surfaceOrientation, surfaceRect);
940 mainCommandBuffer->BeginRenderPass(
946 mainCommandBuffer->SetViewport({float(viewportRect.x),
947 float(viewportRect.y),
948 float(viewportRect.width),
949 float(viewportRect.height)});
951 // Clear the list of bound textures
952 mImpl->boundTextures.Clear();
954 mImpl->renderAlgorithms.ProcessRenderInstruction(
956 mImpl->renderBufferIndex,
957 depthBufferAvailable,
958 stencilBufferAvailable,
959 mImpl->boundTextures,
963 Uint16Pair(surfaceRect.width, surfaceRect.height));
965 Graphics::SyncObject* syncObject{nullptr};
966 // If the render instruction has an associated render tracker (owned separately)
967 // and framebuffer, create a one shot sync object, and use it to determine when
968 // the render pass has finished executing on GPU.
969 if(instruction.mRenderTracker && instruction.mFrameBuffer)
971 syncObject = instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController);
972 instruction.mRenderTracker = nullptr;
974 mainCommandBuffer->EndRenderPass(syncObject);
977 // Unlock standalone uniform buffer.
978 mImpl->uniformBufferManager->UnlockUniformBuffer(mImpl->renderBufferIndex);
980 mImpl->renderAlgorithms.SubmitCommandBuffer();
981 mImpl->commandBufferSubmitted = true;
983 std::sort(targetstoPresent.begin(), targetstoPresent.end());
985 Graphics::RenderTarget* rt = nullptr;
986 for(auto& target : targetstoPresent)
990 mImpl->graphicsController.PresentRenderTarget(target);
996 void RenderManager::PostRender()
998 if(!mImpl->commandBufferSubmitted)
1000 // Rendering is skipped but there may be pending tasks. Flush them.
1001 Graphics::SubmitInfo submitInfo;
1002 submitInfo.cmdBuffer.clear(); // Only flush
1003 submitInfo.flags = 0 | Graphics::SubmitFlagBits::FLUSH;
1004 mImpl->graphicsController.SubmitCommandBuffers(submitInfo);
1006 mImpl->commandBufferSubmitted = true;
1009 // Notify RenderGeometries that rendering has finished
1010 for(auto&& iter : mImpl->geometryContainer)
1012 iter->OnRenderFinished();
1015 // Notify RenderTexture that rendering has finished
1016 for(auto&& iter : mImpl->textureContainer)
1018 iter->OnRenderFinished();
1021 mImpl->UpdateTrackers();
1023 uint32_t count = 0u;
1024 for(auto& scene : mImpl->sceneContainer)
1026 count += scene->GetRenderInstructions().Count(mImpl->renderBufferIndex);
1029 const bool haveInstructions = count > 0u;
1031 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1032 mImpl->lastFrameWasRendered = haveInstructions;
1035 * The rendering has finished; swap to the next buffer.
1036 * Ideally the update has just finished using this buffer; otherwise the render thread
1037 * should block until the update has finished.
1039 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1041 DALI_PRINT_RENDER_END();
1044 } // namespace SceneGraph
1046 } // namespace Internal