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>
27 #include <dali/internal/common/ordered-set.h>
29 #include <dali/internal/event/common/scene-impl.h>
31 #include <dali/internal/update/common/scene-graph-scene.h>
32 #include <dali/internal/update/nodes/scene-graph-layer.h>
33 #include <dali/internal/update/render-tasks/scene-graph-camera.h>
35 #include <dali/internal/common/owner-key-container.h>
37 #include <dali/internal/render/common/render-algorithms.h>
38 #include <dali/internal/render/common/render-debug.h>
39 #include <dali/internal/render/common/render-instruction.h>
40 #include <dali/internal/render/common/render-tracker.h>
41 #include <dali/internal/render/queue/render-queue.h>
42 #include <dali/internal/render/renderers/pipeline-cache.h>
43 #include <dali/internal/render/renderers/render-frame-buffer.h>
44 #include <dali/internal/render/renderers/render-texture.h>
45 #include <dali/internal/render/renderers/shader-cache.h>
46 #include <dali/internal/render/renderers/uniform-buffer-manager.h>
47 #include <dali/internal/render/renderers/uniform-buffer-view-pool.h>
48 #include <dali/internal/render/shaders/program-controller.h>
58 #if defined(DEBUG_ENABLED)
61 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER");
62 } // unnamed namespace
67 inline Graphics::Rect2D RecalculateScissorArea(Graphics::Rect2D scissorArea, int orientation, Rect<int32_t> viewportRect)
69 Graphics::Rect2D newScissorArea;
73 newScissorArea.x = viewportRect.height - (scissorArea.y + scissorArea.height);
74 newScissorArea.y = scissorArea.x;
75 newScissorArea.width = scissorArea.height;
76 newScissorArea.height = scissorArea.width;
78 else if(orientation == 180)
80 newScissorArea.x = viewportRect.width - (scissorArea.x + scissorArea.width);
81 newScissorArea.y = viewportRect.height - (scissorArea.y + scissorArea.height);
82 newScissorArea.width = scissorArea.width;
83 newScissorArea.height = scissorArea.height;
85 else if(orientation == 270)
87 newScissorArea.x = scissorArea.y;
88 newScissorArea.y = viewportRect.width - (scissorArea.x + scissorArea.width);
89 newScissorArea.width = scissorArea.height;
90 newScissorArea.height = scissorArea.width;
94 newScissorArea.x = scissorArea.x;
95 newScissorArea.y = scissorArea.y;
96 newScissorArea.width = scissorArea.width;
97 newScissorArea.height = scissorArea.height;
99 return newScissorArea;
104 * Structure to contain internal data
106 struct RenderManager::Impl
108 Impl(Graphics::Controller& graphicsController,
109 Integration::DepthBufferAvailable depthBufferAvailableParam,
110 Integration::StencilBufferAvailable stencilBufferAvailableParam,
111 Integration::PartialUpdateAvailable partialUpdateAvailableParam)
112 : graphicsController(graphicsController),
113 renderAlgorithms(graphicsController),
114 programController(graphicsController),
115 shaderCache(graphicsController),
116 depthBufferAvailable(depthBufferAvailableParam),
117 stencilBufferAvailable(stencilBufferAvailableParam),
118 partialUpdateAvailable(partialUpdateAvailableParam)
120 // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
121 threadPool = std::make_unique<Dali::ThreadPool>();
122 threadPool->Initialize(1u);
124 uniformBufferManager = std::make_unique<Render::UniformBufferManager>(&graphicsController);
125 pipelineCache = std::make_unique<Render::PipelineCache>(graphicsController);
130 threadPool.reset(nullptr); // reset now to maintain correct destruction order
131 rendererContainer.Clear(); // clear now before the pipeline cache is deleted
134 void AddRenderTracker(Render::RenderTracker* renderTracker)
136 DALI_ASSERT_DEBUG(renderTracker != nullptr);
137 mRenderTrackers.PushBack(renderTracker);
140 void RemoveRenderTracker(Render::RenderTracker* renderTracker)
142 mRenderTrackers.EraseObject(renderTracker);
145 void UpdateTrackers()
147 for(auto&& iter : mRenderTrackers)
149 iter->PollSyncObject();
153 // the order is important for destruction,
154 Graphics::Controller& graphicsController;
155 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
156 std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
157 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
159 OrderedSet<Render::Sampler> samplerContainer; ///< List of owned samplers
160 OrderedSet<Render::FrameBuffer> frameBufferContainer; ///< List of owned framebuffers
161 OrderedSet<Render::VertexBuffer> vertexBufferContainer; ///< List of owned vertex buffers
162 OrderedSet<Render::Geometry> geometryContainer; ///< List of owned Geometries
163 OwnerKeyContainer<Render::Renderer> rendererContainer; ///< List of owned renderers
164 OwnerKeyContainer<Render::Texture> textureContainer; ///< List of owned textures
166 OrderedSet<Render::RenderTracker> mRenderTrackers; ///< List of owned render trackers
168 ProgramController programController; ///< Owner of the programs
169 Render::ShaderCache shaderCache; ///< The cache for the graphics shaders
171 std::unique_ptr<Render::UniformBufferManager> uniformBufferManager; ///< The uniform buffer manager
172 std::unique_ptr<Render::PipelineCache> pipelineCache;
174 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
175 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
176 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
178 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
179 Vector<Graphics::Texture*> boundTextures; ///< The textures bound for rendering
180 Vector<Graphics::Texture*> textureDependencyList; ///< The dependency list of bound textures
181 Vector<Render::TextureKey> updatedTextures{}; ///< The updated texture list
183 uint32_t frameCount{0u}; ///< The current frame count
184 BufferIndex renderBufferIndex{SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX}; ///< The index of the buffer to read from; this is opposite of the "update" buffer
186 bool lastFrameWasRendered{false}; ///< Keeps track of the last frame being rendered due to having render instructions
187 bool commandBufferSubmitted{false};
190 RenderManager* RenderManager::New(Graphics::Controller& graphicsController,
191 Integration::DepthBufferAvailable depthBufferAvailable,
192 Integration::StencilBufferAvailable stencilBufferAvailable,
193 Integration::PartialUpdateAvailable partialUpdateAvailable)
195 auto* manager = new RenderManager;
196 manager->mImpl = new Impl(graphicsController,
197 depthBufferAvailable,
198 stencilBufferAvailable,
199 partialUpdateAvailable);
203 RenderManager::RenderManager()
208 RenderManager::~RenderManager()
213 RenderQueue& RenderManager::GetRenderQueue()
215 return mImpl->renderQueue;
218 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
222 void RenderManager::AddRenderer(const Render::RendererKey& renderer)
224 // Initialize the renderer as we are now in render thread
225 renderer->Initialize(mImpl->graphicsController, mImpl->programController, mImpl->shaderCache, *(mImpl->uniformBufferManager.get()), *(mImpl->pipelineCache.get()));
227 mImpl->rendererContainer.PushBack(renderer);
230 void RenderManager::RemoveRenderer(const Render::RendererKey& renderer)
232 mImpl->rendererContainer.EraseKey(renderer);
235 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
237 sampler->Initialize(mImpl->graphicsController);
238 mImpl->samplerContainer.PushBack(sampler.Release());
241 void RenderManager::RemoveSampler(Render::Sampler* sampler)
243 mImpl->samplerContainer.EraseObject(sampler);
246 void RenderManager::AddTexture(const Render::TextureKey& textureKey)
248 DALI_ASSERT_DEBUG(textureKey && "Trying to add empty texture key");
250 textureKey->Initialize(mImpl->graphicsController);
251 mImpl->textureContainer.PushBack(textureKey);
252 mImpl->updatedTextures.PushBack(textureKey);
255 void RenderManager::RemoveTexture(const Render::TextureKey& textureKey)
257 DALI_ASSERT_DEBUG(textureKey && "Trying to remove empty texture key");
259 // Find the texture, use std::find so we can do the erase by iterator safely
260 auto iter = std::find(mImpl->textureContainer.Begin(), mImpl->textureContainer.End(), textureKey);
262 if(iter != mImpl->textureContainer.End())
264 textureKey->Destroy();
265 mImpl->textureContainer.Erase(iter); // Texture found; now destroy it
269 void RenderManager::UploadTexture(const Render::TextureKey& textureKey, PixelDataPtr pixelData, const Texture::UploadParams& params)
271 DALI_ASSERT_DEBUG(textureKey && "Trying to upload to empty texture key");
272 textureKey->Upload(pixelData, params);
274 mImpl->updatedTextures.PushBack(textureKey);
277 void RenderManager::GenerateMipmaps(const Render::TextureKey& textureKey)
279 DALI_ASSERT_DEBUG(textureKey && "Trying to generate mipmaps on empty texture key");
280 textureKey->GenerateMipmaps();
282 mImpl->updatedTextures.PushBack(textureKey);
285 void RenderManager::SetTextureUpdated(const Render::TextureKey& textureKey)
287 DALI_ASSERT_DEBUG(textureKey && "Trying to set updated on empty texture key");
288 textureKey->SetUpdated(true);
290 mImpl->updatedTextures.PushBack(textureKey);
293 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
295 sampler->SetFilterMode(static_cast<Dali::FilterMode::Type>(minFilterMode),
296 static_cast<Dali::FilterMode::Type>(magFilterMode));
299 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
301 sampler->SetWrapMode(static_cast<Dali::WrapMode::Type>(rWrapMode),
302 static_cast<Dali::WrapMode::Type>(sWrapMode),
303 static_cast<Dali::WrapMode::Type>(tWrapMode));
306 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
308 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
309 mImpl->frameBufferContainer.PushBack(frameBufferPtr);
310 frameBufferPtr->Initialize(mImpl->graphicsController);
313 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
315 DALI_ASSERT_DEBUG(nullptr != frameBuffer);
317 // Find the framebuffer, use OrderedSet.Find so we can safely do the erase
318 auto iter = mImpl->frameBufferContainer.Find(frameBuffer);
320 if(iter != mImpl->frameBufferContainer.End())
322 frameBuffer->Destroy();
323 mImpl->frameBufferContainer.Erase(iter); // frameBuffer found; now destroy it
327 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
329 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
330 mImpl->sceneContainer.push_back(scene);
333 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
335 auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
336 if(iter != mImpl->sceneContainer.end())
338 mImpl->sceneContainer.erase(iter);
342 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
344 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
347 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
349 frameBuffer->AttachColorTexture(texture, mipmapLevel, layer);
352 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
354 frameBuffer->AttachDepthTexture(texture, mipmapLevel);
357 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
359 frameBuffer->AttachDepthStencilTexture(texture, mipmapLevel);
362 void RenderManager::SetMultiSamplingLevelToFrameBuffer(Render::FrameBuffer* frameBuffer, uint8_t multiSamplingLevel)
364 frameBuffer->SetMultiSamplingLevel(multiSamplingLevel);
367 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
369 mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
372 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
374 mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
377 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
379 vertexBuffer->SetFormat(format.Release());
382 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
384 vertexBuffer->SetData(data.Release(), size);
387 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Render::Geometry::Uint16ContainerType& indices)
389 geometry->SetIndexBuffer(indices);
392 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Render::Geometry::Uint32ContainerType& indices)
394 geometry->SetIndexBuffer(indices);
397 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
399 mImpl->geometryContainer.PushBack(geometry.Release());
402 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
404 mImpl->geometryContainer.EraseObject(geometry);
407 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
409 geometry->AddVertexBuffer(vertexBuffer);
412 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
414 geometry->RemoveVertexBuffer(vertexBuffer);
417 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
419 geometry->SetType(Render::Geometry::Type(geometryType));
422 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
424 mImpl->AddRenderTracker(renderTracker);
427 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
429 mImpl->RemoveRenderTracker(renderTracker);
432 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear)
434 DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
437 mImpl->uniformBufferManager->GetUniformBufferViewPool(mImpl->renderBufferIndex)->Rollback();
439 // Increment the frame count at the beginning of each frame
442 // Process messages queued during previous update
443 mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
446 for(auto& i : mImpl->sceneContainer)
448 count += i->GetRenderInstructions().Count(mImpl->renderBufferIndex);
451 const bool haveInstructions = count > 0u;
453 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");
455 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
456 if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
458 DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
460 // Upload the geometries
461 for(auto&& geom : mImpl->geometryContainer)
463 geom->Upload(mImpl->graphicsController);
467 // Reset pipeline cache before rendering
468 mImpl->pipelineCache->PreRender();
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 || 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();
722 Rect<int> clippingRect = sceneObject->GetSurfaceRect();
723 RenderScene(status, scene, renderToFbo, clippingRect);
726 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
728 if(mImpl->partialUpdateAvailable == Integration::PartialUpdateAvailable::TRUE && !renderToFbo && clippingRect.IsEmpty())
730 // ClippingRect is empty. Skip rendering
734 // Reset main algorithms command buffer
735 mImpl->renderAlgorithms.ResetCommandBuffer();
737 auto mainCommandBuffer = mImpl->renderAlgorithms.GetMainCommandBuffer();
739 Internal::Scene& sceneInternal = GetImplementation(scene);
740 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
746 uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
748 std::vector<Graphics::RenderTarget*> targetstoPresent;
750 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
751 if(clippingRect == surfaceRect)
753 // Full rendering case
754 // Make clippingRect empty because we're doing full rendering now if the clippingRect is empty.
755 // To reduce side effects, keep this logic now.
756 clippingRect = Rect<int>();
759 // Prepare to lock and map standalone uniform buffer.
760 mImpl->uniformBufferManager->ReadyToLockUniformBuffer(mImpl->renderBufferIndex);
762 for(uint32_t i = 0; i < count; ++i)
764 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
766 if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
771 // Mark that we will require a post-render step to be performed (includes swap-buffers).
772 status.SetNeedsPostRender(true);
774 Rect<int32_t> viewportRect;
776 int32_t surfaceOrientation = sceneObject->GetSurfaceOrientation() + sceneObject->GetScreenOrientation();
777 if(surfaceOrientation >= 360)
779 surfaceOrientation -= 360;
782 // @todo Should these be part of scene?
783 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
784 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
786 Graphics::RenderTarget* currentRenderTarget = nullptr;
787 Graphics::RenderPass* currentRenderPass = nullptr;
788 std::vector<Graphics::ClearValue> currentClearValues{};
790 if(instruction.mFrameBuffer)
792 // Ensure graphics framebuffer is created, bind attachments and create render passes
793 // Only happens once per framebuffer. If the create fails, e.g. no attachments yet,
794 // then don't render to this framebuffer.
795 if(!instruction.mFrameBuffer->GetGraphicsObject())
797 const bool created = instruction.mFrameBuffer->CreateGraphicsObjects();
804 auto& clearValues = instruction.mFrameBuffer->GetGraphicsRenderPassClearValues();
806 // Set the clear color for first color attachment
807 if(instruction.mIsClearColorSet && !clearValues.empty())
809 clearValues[0].color = {
810 instruction.mClearColor.r,
811 instruction.mClearColor.g,
812 instruction.mClearColor.b,
813 instruction.mClearColor.a};
816 currentClearValues = clearValues;
818 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
821 currentRenderTarget = instruction.mFrameBuffer->GetGraphicsRenderTarget();
822 currentRenderPass = instruction.mFrameBuffer->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
824 else // no framebuffer
827 auto& clearValues = sceneObject->GetGraphicsRenderPassClearValues();
829 if(instruction.mIsClearColorSet)
831 clearValues[0].color = {
832 instruction.mClearColor.r,
833 instruction.mClearColor.g,
834 instruction.mClearColor.b,
835 instruction.mClearColor.a};
838 currentClearValues = clearValues;
840 // @todo SceneObject should already have the depth clear / stencil clear in the clearValues array.
841 // if the window has a depth/stencil buffer.
842 if((depthBufferAvailable == Integration::DepthBufferAvailable::TRUE ||
843 stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE) &&
844 (currentClearValues.size() <= 1))
846 currentClearValues.emplace_back();
847 currentClearValues.back().depthStencil.depth = 0;
848 currentClearValues.back().depthStencil.stencil = 0;
851 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
853 currentRenderTarget = sceneObject->GetSurfaceRenderTarget();
854 currentRenderPass = sceneObject->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
857 targetstoPresent.emplace_back(currentRenderTarget);
859 // reset the program matrices for all programs once per frame
860 // this ensures we will set view and projection matrix once per program per camera
861 mImpl->programController.ResetProgramMatrices();
863 if(instruction.mFrameBuffer)
865 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
866 for(unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
868 mImpl->textureDependencyList.PushBack(instruction.mFrameBuffer->GetTexture(i0));
872 if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
874 // Offscreen buffer rendering
875 if(instruction.mIsViewportSet)
877 // For Viewport the lower-left corner is (0,0)
878 const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
879 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
883 viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
885 surfaceOrientation = 0;
887 else // No Offscreen frame buffer rendering
889 // Check whether a viewport is specified, otherwise the full surface size is used
890 if(instruction.mIsViewportSet)
892 // For Viewport the lower-left corner is (0,0)
893 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
894 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
898 viewportRect = surfaceRect;
902 // Set surface orientation
903 // @todo Inform graphics impl by another route.
904 // was: mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
906 /*** Clear region of framebuffer or surface before drawing ***/
907 bool clearFullFrameRect = (surfaceRect == viewportRect);
908 if(instruction.mFrameBuffer != nullptr)
910 Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
911 clearFullFrameRect = (frameRect == viewportRect);
914 if(!clippingRect.IsEmpty())
916 if(!clippingRect.Intersect(viewportRect))
918 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
919 clippingRect = Rect<int>();
921 clearFullFrameRect = false;
924 Graphics::Rect2D scissorArea{viewportRect.x, viewportRect.y, uint32_t(viewportRect.width), uint32_t(viewportRect.height)};
925 if(instruction.mIsClearColorSet)
927 if(!clearFullFrameRect)
929 if(!clippingRect.IsEmpty())
931 scissorArea = {clippingRect.x, clippingRect.y, uint32_t(clippingRect.width), uint32_t(clippingRect.height)};
936 // Scissor's value should be set based on the default system coordinates.
937 // When the surface is rotated, the input values already were set with the rotated angle.
938 // So, re-calculation is needed.
939 scissorArea = RecalculateScissorArea(scissorArea, surfaceOrientation, surfaceRect);
942 mainCommandBuffer->BeginRenderPass(
948 mainCommandBuffer->SetViewport({float(viewportRect.x),
949 float(viewportRect.y),
950 float(viewportRect.width),
951 float(viewportRect.height)});
953 // Clear the list of bound textures
954 mImpl->boundTextures.Clear();
956 mImpl->renderAlgorithms.ProcessRenderInstruction(
958 mImpl->renderBufferIndex,
959 depthBufferAvailable,
960 stencilBufferAvailable,
961 mImpl->boundTextures,
965 Uint16Pair(surfaceRect.width, surfaceRect.height));
967 Graphics::SyncObject* syncObject{nullptr};
968 // If the render instruction has an associated render tracker (owned separately)
969 // and framebuffer, create a one shot sync object, and use it to determine when
970 // the render pass has finished executing on GPU.
971 if(instruction.mRenderTracker && instruction.mFrameBuffer)
973 syncObject = instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController);
974 instruction.mRenderTracker = nullptr;
976 mainCommandBuffer->EndRenderPass(syncObject);
979 // Unlock standalone uniform buffer.
980 mImpl->uniformBufferManager->UnlockUniformBuffer(mImpl->renderBufferIndex);
982 mImpl->renderAlgorithms.SubmitCommandBuffer();
983 mImpl->commandBufferSubmitted = true;
985 std::sort(targetstoPresent.begin(), targetstoPresent.end());
987 Graphics::RenderTarget* rt = nullptr;
988 for(auto& target : targetstoPresent)
992 mImpl->graphicsController.PresentRenderTarget(target);
998 void RenderManager::PostRender()
1000 if(!mImpl->commandBufferSubmitted)
1002 // Rendering is skipped but there may be pending tasks. Flush them.
1003 Graphics::SubmitInfo submitInfo;
1004 submitInfo.cmdBuffer.clear(); // Only flush
1005 submitInfo.flags = 0 | Graphics::SubmitFlagBits::FLUSH;
1006 mImpl->graphicsController.SubmitCommandBuffers(submitInfo);
1008 mImpl->commandBufferSubmitted = true;
1011 // Notify RenderGeometries that rendering has finished
1012 for(auto&& iter : mImpl->geometryContainer)
1014 iter->OnRenderFinished();
1017 // Notify updated RenderTexture that rendering has finished
1018 for(auto&& iter : mImpl->updatedTextures)
1020 iter->OnRenderFinished();
1022 mImpl->updatedTextures.Clear();
1024 mImpl->UpdateTrackers();
1026 uint32_t count = 0u;
1027 for(auto& scene : mImpl->sceneContainer)
1029 count += scene->GetRenderInstructions().Count(mImpl->renderBufferIndex);
1032 const bool haveInstructions = count > 0u;
1034 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1035 mImpl->lastFrameWasRendered = haveInstructions;
1038 * The rendering has finished; swap to the next buffer.
1039 * Ideally the update has just finished using this buffer; otherwise the render thread
1040 * should block until the update has finished.
1042 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1044 DALI_PRINT_RENDER_END();
1047 } // namespace SceneGraph
1049 } // namespace Internal