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/uniform-buffer-manager.h>
46 #include <dali/internal/render/renderers/uniform-buffer.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 // TODO : Cache clean logic have some problem now. Just block it until bug resolved
67 //constexpr uint32_t CACHE_CLEAN_FRAME_COUNT = 600u; // 60fps * 10sec
69 inline Graphics::Rect2D RecalculateScissorArea(const Graphics::Rect2D& scissorArea, int orientation, const Rect<int32_t>& viewportRect)
71 Graphics::Rect2D newScissorArea;
75 newScissorArea.x = viewportRect.height - (scissorArea.y + scissorArea.height);
76 newScissorArea.y = scissorArea.x;
77 newScissorArea.width = scissorArea.height;
78 newScissorArea.height = scissorArea.width;
80 else if(orientation == 180)
82 newScissorArea.x = viewportRect.width - (scissorArea.x + scissorArea.width);
83 newScissorArea.y = viewportRect.height - (scissorArea.y + scissorArea.height);
84 newScissorArea.width = scissorArea.width;
85 newScissorArea.height = scissorArea.height;
87 else if(orientation == 270)
89 newScissorArea.x = scissorArea.y;
90 newScissorArea.y = viewportRect.width - (scissorArea.x + scissorArea.width);
91 newScissorArea.width = scissorArea.height;
92 newScissorArea.height = scissorArea.width;
96 newScissorArea.x = scissorArea.x;
97 newScissorArea.y = scissorArea.y;
98 newScissorArea.width = scissorArea.width;
99 newScissorArea.height = scissorArea.height;
101 return newScissorArea;
104 inline Rect<int32_t> CalculateUpdateArea(RenderItem& item, BufferIndex renderBufferIndex, const Rect<int32_t>& viewportRect)
107 if(item.mNode && item.mNode->IsTextureUpdateAreaUsed() && item.mRenderer)
109 updateArea = item.mRenderer->GetTextureUpdateArea();
113 updateArea = item.mRenderer ? item.mRenderer->GetVisualTransformedUpdateArea(renderBufferIndex, item.mUpdateArea) : item.mUpdateArea;
116 return RenderItem::CalculateViewportSpaceAABB(item.mModelViewMatrix, Vector3(updateArea.x, updateArea.y, 0.0f), Vector3(updateArea.z, updateArea.w, 0.0f), viewportRect.width, viewportRect.height);
119 inline void AlignDamagedRect(Rect<int32_t>& rect)
121 const int left = rect.x;
122 const int top = rect.y;
123 const int right = rect.x + rect.width;
124 const int bottom = rect.y + rect.height;
125 rect.x = (left / 16) * 16;
126 rect.y = (top / 16) * 16;
127 rect.width = ((right + 16) / 16) * 16 - rect.x;
128 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
133 * Structure to contain internal data
135 struct RenderManager::Impl
137 Impl(Graphics::Controller& graphicsController,
138 Integration::DepthBufferAvailable depthBufferAvailableParam,
139 Integration::StencilBufferAvailable stencilBufferAvailableParam,
140 Integration::PartialUpdateAvailable partialUpdateAvailableParam)
141 : graphicsController(graphicsController),
142 renderAlgorithms(graphicsController),
143 programController(graphicsController),
144 depthBufferAvailable(depthBufferAvailableParam),
145 stencilBufferAvailable(stencilBufferAvailableParam),
146 partialUpdateAvailable(partialUpdateAvailableParam)
148 // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
149 threadPool = std::make_unique<Dali::ThreadPool>();
150 threadPool->Initialize(1u);
152 uniformBufferManager = std::make_unique<Render::UniformBufferManager>(&graphicsController);
153 pipelineCache = std::make_unique<Render::PipelineCache>(graphicsController);
158 threadPool.reset(nullptr); // reset now to maintain correct destruction order
159 rendererContainer.Clear(); // clear now before the pipeline cache is deleted
162 void AddRenderTracker(Render::RenderTracker* renderTracker)
164 DALI_ASSERT_DEBUG(renderTracker != nullptr);
165 mRenderTrackers.PushBack(renderTracker);
168 void RemoveRenderTracker(Render::RenderTracker* renderTracker)
170 mRenderTrackers.EraseObject(renderTracker);
173 void UpdateTrackers()
175 for(auto&& iter : mRenderTrackers)
177 iter->PollSyncObject();
181 // the order is important for destruction,
182 Graphics::Controller& graphicsController;
183 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
184 std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
185 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
187 OrderedSet<Render::Sampler> samplerContainer; ///< List of owned samplers
188 OrderedSet<Render::FrameBuffer> frameBufferContainer; ///< List of owned framebuffers
189 OrderedSet<Render::VertexBuffer> vertexBufferContainer; ///< List of owned vertex buffers
190 OrderedSet<Render::Geometry> geometryContainer; ///< List of owned Geometries
191 OwnerKeyContainer<Render::Renderer> rendererContainer; ///< List of owned renderers
192 OwnerKeyContainer<Render::Texture> textureContainer; ///< List of owned textures
194 OrderedSet<Render::RenderTracker> mRenderTrackers; ///< List of owned render trackers
196 OwnerKeyContainer<Render::Texture> textureDiscardQueue; ///< Discarded textures
198 ProgramController programController; ///< Owner of the programs
200 std::unique_ptr<Render::UniformBufferManager> uniformBufferManager; ///< The uniform buffer manager
201 std::unique_ptr<Render::PipelineCache> pipelineCache;
203 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
204 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
205 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
207 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
208 Vector<Render::TextureKey> updatedTextures{}; ///< The updated texture list
210 uint32_t frameCount{0u}; ///< The current frame count
211 BufferIndex renderBufferIndex{SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX}; ///< The index of the buffer to read from;
213 bool lastFrameWasRendered{false}; ///< Keeps track of the last frame being rendered due to having render instructions
214 bool commandBufferSubmitted{false};
217 RenderManager* RenderManager::New(Graphics::Controller& graphicsController,
218 Integration::DepthBufferAvailable depthBufferAvailable,
219 Integration::StencilBufferAvailable stencilBufferAvailable,
220 Integration::PartialUpdateAvailable partialUpdateAvailable)
222 auto* manager = new RenderManager;
223 manager->mImpl = new Impl(graphicsController,
224 depthBufferAvailable,
225 stencilBufferAvailable,
226 partialUpdateAvailable);
230 RenderManager::RenderManager()
235 RenderManager::~RenderManager()
240 RenderQueue& RenderManager::GetRenderQueue()
242 return mImpl->renderQueue;
245 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
249 void RenderManager::AddRenderer(const Render::RendererKey& renderer)
251 // Initialize the renderer as we are now in render thread
252 renderer->Initialize(mImpl->graphicsController, mImpl->programController, *(mImpl->uniformBufferManager.get()), *(mImpl->pipelineCache.get()));
254 mImpl->rendererContainer.PushBack(renderer);
257 void RenderManager::RemoveRenderer(const Render::RendererKey& renderer)
259 mImpl->rendererContainer.EraseKey(renderer);
262 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
264 sampler->Initialize(mImpl->graphicsController);
265 mImpl->samplerContainer.PushBack(sampler.Release());
268 void RenderManager::RemoveSampler(Render::Sampler* sampler)
270 mImpl->samplerContainer.EraseObject(sampler);
273 void RenderManager::AddTexture(const Render::TextureKey& textureKey)
275 DALI_ASSERT_DEBUG(textureKey && "Trying to add empty texture key");
277 textureKey->Initialize(mImpl->graphicsController, *this);
278 mImpl->textureContainer.PushBack(textureKey);
279 mImpl->updatedTextures.PushBack(textureKey);
282 void RenderManager::RemoveTexture(const Render::TextureKey& textureKey)
284 DALI_ASSERT_DEBUG(textureKey && "Trying to remove empty texture key");
286 // Find the texture, use std::find so we can do the erase by iterator safely
287 auto iter = std::find(mImpl->textureContainer.Begin(), mImpl->textureContainer.End(), textureKey);
289 if(iter != mImpl->textureContainer.End())
292 textureKey->Destroy();
294 // Transfer ownership to the discard queue, this keeps the object alive, until the render-thread has finished with it
295 mImpl->textureDiscardQueue.PushBack(mImpl->textureContainer.Release(iter));
299 void RenderManager::UploadTexture(const Render::TextureKey& textureKey, PixelDataPtr pixelData, const Graphics::UploadParams& params)
301 DALI_ASSERT_DEBUG(textureKey && "Trying to upload to empty texture key");
302 textureKey->Upload(pixelData, params);
304 mImpl->updatedTextures.PushBack(textureKey);
307 void RenderManager::GenerateMipmaps(const Render::TextureKey& textureKey)
309 DALI_ASSERT_DEBUG(textureKey && "Trying to generate mipmaps on empty texture key");
310 textureKey->GenerateMipmaps();
312 mImpl->updatedTextures.PushBack(textureKey);
315 void RenderManager::SetTextureSize(const Render::TextureKey& textureKey, const Dali::ImageDimensions& size)
317 DALI_ASSERT_DEBUG(textureKey && "Trying to set size on empty texture key");
318 textureKey->SetWidth(size.GetWidth());
319 textureKey->SetHeight(size.GetHeight());
322 void RenderManager::SetTextureFormat(const Render::TextureKey& textureKey, Dali::Pixel::Format pixelFormat)
324 DALI_ASSERT_DEBUG(textureKey && "Trying to set pixel format on empty texture key");
325 textureKey->SetPixelFormat(pixelFormat);
328 void RenderManager::SetTextureUpdated(const Render::TextureKey& textureKey)
330 DALI_ASSERT_DEBUG(textureKey && "Trying to set updated on empty texture key");
331 textureKey->SetUpdated(true);
333 mImpl->updatedTextures.PushBack(textureKey);
336 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
338 sampler->SetFilterMode(static_cast<Dali::FilterMode::Type>(minFilterMode),
339 static_cast<Dali::FilterMode::Type>(magFilterMode));
342 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
344 sampler->SetWrapMode(static_cast<Dali::WrapMode::Type>(rWrapMode),
345 static_cast<Dali::WrapMode::Type>(sWrapMode),
346 static_cast<Dali::WrapMode::Type>(tWrapMode));
349 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
351 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
352 mImpl->frameBufferContainer.PushBack(frameBufferPtr);
353 frameBufferPtr->Initialize(mImpl->graphicsController);
356 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
358 DALI_ASSERT_DEBUG(nullptr != frameBuffer);
360 // Find the framebuffer, use OrderedSet.Find so we can safely do the erase
361 auto iter = mImpl->frameBufferContainer.Find(frameBuffer);
363 if(iter != mImpl->frameBufferContainer.End())
365 frameBuffer->Destroy();
366 mImpl->frameBufferContainer.Erase(iter); // frameBuffer found; now destroy it
370 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
372 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
373 mImpl->sceneContainer.push_back(scene);
374 mImpl->uniformBufferManager->RegisterScene(scene);
377 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
379 mImpl->uniformBufferManager->UnregisterScene(scene);
380 auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
381 if(iter != mImpl->sceneContainer.end())
383 mImpl->sceneContainer.erase(iter);
387 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
389 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
392 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
394 frameBuffer->AttachColorTexture(texture, mipmapLevel, layer);
397 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
399 frameBuffer->AttachDepthTexture(texture, mipmapLevel);
402 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
404 frameBuffer->AttachDepthStencilTexture(texture, mipmapLevel);
407 void RenderManager::SetMultiSamplingLevelToFrameBuffer(Render::FrameBuffer* frameBuffer, uint8_t multiSamplingLevel)
409 frameBuffer->SetMultiSamplingLevel(multiSamplingLevel);
412 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
414 mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
417 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
419 mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
422 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
424 vertexBuffer->SetFormat(format.Release());
427 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
429 vertexBuffer->SetData(data.Release(), size);
432 void RenderManager::SetVertexBufferUpdateCallback(Render::VertexBuffer* vertexBuffer, Dali::VertexBufferUpdateCallback* callback)
434 vertexBuffer->SetVertexBufferUpdateCallback(callback);
437 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Render::Geometry::Uint16ContainerType& indices)
439 geometry->SetIndexBuffer(indices);
442 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Render::Geometry::Uint32ContainerType& indices)
444 geometry->SetIndexBuffer(indices);
447 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
449 mImpl->geometryContainer.PushBack(geometry.Release());
452 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
454 mImpl->geometryContainer.EraseObject(geometry);
457 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
459 geometry->AddVertexBuffer(vertexBuffer);
462 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
464 geometry->RemoveVertexBuffer(vertexBuffer);
467 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
469 geometry->SetType(Render::Geometry::Type(geometryType));
472 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
474 mImpl->AddRenderTracker(renderTracker);
477 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
479 mImpl->RemoveRenderTracker(renderTracker);
482 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear)
484 DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
485 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "\n\nNewFrame %d\n", mImpl->frameCount);
487 // Increment the frame count at the beginning of each frame
490 // Process messages queued during previous update
491 mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
493 uint32_t totalInstructionCount = 0u;
494 for(auto& i : mImpl->sceneContainer)
496 totalInstructionCount += i->GetRenderInstructions().Count(mImpl->renderBufferIndex);
499 const bool haveInstructions = totalInstructionCount > 0u;
501 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");
503 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
504 if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
506 DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
508 // Upload the geometries
509 for(auto&& geom : mImpl->geometryContainer)
511 geom->Upload(mImpl->graphicsController);
515 // Reset pipeline cache before rendering
516 mImpl->pipelineCache->PreRender();
518 // Let we collect reference counts during CACHE_CLEAN_FRAME_COUNT frames.
519 // TODO : Cache clean logic have some problem now. Just block it until bug resolved
521 if(mImpl->frameCount % CACHE_CLEAN_FRAME_COUNT == 1)
523 mImpl->programController.ResetReferenceCount();
527 mImpl->commandBufferSubmitted = false;
530 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
532 if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
537 Internal::Scene& sceneInternal = GetImplementation(scene);
538 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
540 if(!sceneObject || sceneObject->IsRenderingSkipped())
542 // We don't need to calculate dirty rects
546 class DamagedRectsCleaner
549 explicit DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects, Rect<int>& surfaceRect)
550 : mDamagedRects(damagedRects),
551 mSurfaceRect(surfaceRect),
556 void SetCleanOnReturn(bool cleanOnReturn)
558 mCleanOnReturn = cleanOnReturn;
561 ~DamagedRectsCleaner()
565 mDamagedRects.clear();
566 mDamagedRects.push_back(mSurfaceRect);
571 std::vector<Rect<int>>& mDamagedRects;
572 Rect<int> mSurfaceRect;
576 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
578 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
579 DamagedRectsCleaner damagedRectCleaner(damagedRects, surfaceRect);
580 bool cleanDamagedRect = false;
582 Scene::ItemsDirtyRectsContainer& itemsDirtyRects = sceneObject->GetItemsDirtyRects();
584 if(!sceneObject->IsPartialUpdateEnabled())
586 // Clear all dirty rects
587 // The rects will be added when partial updated is enabled again
588 itemsDirtyRects.clear();
592 // Mark previous dirty rects in the std::unordered_map.
593 for(auto& dirtyRectPair : itemsDirtyRects)
595 dirtyRectPair.second.visited = false;
598 uint32_t instructionCount = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
599 for(uint32_t i = 0; i < instructionCount; ++i)
601 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
603 if(instruction.mFrameBuffer)
605 cleanDamagedRect = true;
606 continue; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
609 const Camera* camera = instruction.GetCamera();
610 if(camera && camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
614 Quaternion orientation;
615 camera->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
617 Vector3 orientationAxis;
618 Radian orientationAngle;
619 orientation.ToAxisAngle(orientationAxis, orientationAngle);
621 if(position.x > Math::MACHINE_EPSILON_10000 ||
622 position.y > Math::MACHINE_EPSILON_10000 ||
623 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
624 orientationAngle != ANGLE_180 ||
625 scale != Vector3(1.0f, 1.0f, 1.0f))
627 cleanDamagedRect = true;
633 cleanDamagedRect = true;
637 Rect<int32_t> viewportRect;
638 if(instruction.mIsViewportSet)
640 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
641 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
642 if(viewportRect.IsEmpty() || !viewportRect.IsValid())
644 cleanDamagedRect = true;
645 continue; // just skip funny use cases for now, empty viewport means it is set somewhere else
650 viewportRect = surfaceRect;
653 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
654 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
655 if(viewMatrix && projectionMatrix)
657 const RenderListContainer::SizeType count = instruction.RenderListCount();
658 for(RenderListContainer::SizeType index = 0u; index < count; ++index)
660 const RenderList* renderList = instruction.GetRenderList(index);
663 if(!renderList->IsEmpty())
665 const std::size_t listCount = renderList->Count();
666 for(uint32_t listIndex = 0u; listIndex < listCount; ++listIndex)
668 RenderItem& item = renderList->GetItem(listIndex);
669 // If the item does 3D transformation, make full update
670 if(item.mUpdateArea == Vector4::ZERO)
672 cleanDamagedRect = true;
674 // Save the full rect in the damaged list. We need it when this item is removed
675 DirtyRectKey dirtyRectKey(item.mNode, item.mRenderer);
676 auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
677 if(dirtyRectPos != itemsDirtyRects.end())
680 dirtyRectPos->second.visited = true;
681 dirtyRectPos->second.rect = surfaceRect;
685 // Else, just insert the new dirtyrect
686 itemsDirtyRects.insert({dirtyRectKey, surfaceRect});
692 DirtyRectKey dirtyRectKey(item.mNode, item.mRenderer);
693 // If the item refers to updated node or renderer.
694 if(item.mIsUpdated ||
696 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated()))))
698 item.mIsUpdated = false;
700 rect = CalculateUpdateArea(item, mImpl->renderBufferIndex, viewportRect);
701 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
703 AlignDamagedRect(rect);
705 // Found valid dirty rect.
706 auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
707 if(dirtyRectPos != itemsDirtyRects.end())
709 Rect<int> currentRect = rect;
711 // Same item, merge it with the previous rect
712 rect.Merge(dirtyRectPos->second.rect);
714 // Replace the rect as current
715 dirtyRectPos->second.visited = true;
716 dirtyRectPos->second.rect = currentRect;
720 // Else, just insert the new dirtyrect
721 itemsDirtyRects.insert({dirtyRectKey, rect});
724 damagedRects.push_back(rect);
729 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
730 // 2. Mark the related dirty rects as visited so they will not be removed below.
731 auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
732 if(dirtyRectPos != itemsDirtyRects.end())
734 dirtyRectPos->second.visited = true;
738 // The item is not in the list for some reason. Add the current rect!
739 rect = CalculateUpdateArea(item, mImpl->renderBufferIndex, viewportRect);
740 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
742 AlignDamagedRect(rect);
744 itemsDirtyRects.insert({dirtyRectKey, rect});
746 cleanDamagedRect = true; // And make full update at this frame
756 // Check removed nodes or removed renderers dirty rects
757 // Note, std::unordered_map end iterator is validate if we call erase.
758 for(auto iter = itemsDirtyRects.cbegin(), iterEnd = itemsDirtyRects.cend(); iter != iterEnd;)
760 if(!iter->second.visited)
762 damagedRects.push_back(iter->second.rect);
763 iter = itemsDirtyRects.erase(iter);
771 if(sceneObject->IsNeededFullUpdate())
773 cleanDamagedRect = true; // And make full update at this frame
776 if(!cleanDamagedRect)
778 damagedRectCleaner.SetCleanOnReturn(false);
782 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
784 SceneGraph::Scene* sceneObject = GetImplementation(scene).GetSceneObject();
790 Rect<int> clippingRect = sceneObject->GetSurfaceRect();
791 RenderScene(status, scene, renderToFbo, clippingRect);
794 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
796 if(mImpl->partialUpdateAvailable == Integration::PartialUpdateAvailable::TRUE && !renderToFbo && clippingRect.IsEmpty())
798 // ClippingRect is empty. Skip rendering
802 // Reset main algorithms command buffer
803 mImpl->renderAlgorithms.ResetCommandBuffer();
805 auto mainCommandBuffer = mImpl->renderAlgorithms.GetMainCommandBuffer();
807 Internal::Scene& sceneInternal = GetImplementation(scene);
808 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
814 uint32_t instructionCount = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
816 std::vector<Graphics::RenderTarget*> targetstoPresent;
818 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
819 if(clippingRect == surfaceRect)
821 // Full rendering case
822 // Make clippingRect empty because we're doing full rendering now if the clippingRect is empty.
823 // To reduce side effects, keep this logic now.
824 clippingRect = Rect<int>();
827 // Prefetch programs before we start rendering so reflection is
828 // ready, and we can pull exact size of UBO needed (no need to resize during drawing)
829 auto totalSizeCPU = 0u;
830 auto totalSizeGPU = 0u;
832 for(uint32_t i = 0; i < instructionCount; ++i)
834 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
836 if((instruction.mFrameBuffer != nullptr && renderToFbo) ||
837 (instruction.mFrameBuffer == nullptr && !renderToFbo))
839 for(auto j = 0u; j < instruction.RenderListCount(); ++j)
841 const auto& renderList = instruction.GetRenderList(j);
842 for(auto k = 0u; k < renderList->Count(); ++k)
844 auto& item = renderList->GetItem(k);
845 if(item.mRenderer && item.mRenderer->NeedsProgram())
847 // Prepare and store used programs for further processing
848 auto program = item.mRenderer->PrepareProgram(instruction);
851 auto memoryRequirements = program->GetUniformBlocksMemoryRequirements();
853 totalSizeCPU += memoryRequirements.totalCpuSizeRequired;
854 totalSizeGPU += memoryRequirements.totalGpuSizeRequired;
862 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Render scene (%s), CPU:%d GPU:%d\n", renderToFbo ? "Offscreen" : "Onscreen", totalSizeCPU, totalSizeGPU);
864 auto& uboManager = mImpl->uniformBufferManager;
866 uboManager->SetCurrentSceneRenderInfo(sceneObject, renderToFbo);
867 uboManager->Rollback(sceneObject, renderToFbo);
869 // Respec UBOs for this frame (orphan buffers or double buffer in the GPU)
872 uboManager->GetUniformBufferForScene(sceneObject, renderToFbo, true)->ReSpecify(totalSizeCPU);
873 uboManager->GetUniformBufferForScene(sceneObject, renderToFbo, false)->ReSpecify(totalSizeGPU);
876 #if defined(DEBUG_ENABLED)
877 auto uniformBuffer1 = uboManager->GetUniformBufferForScene(sceneObject, renderToFbo, true);
878 auto uniformBuffer2 = uboManager->GetUniformBufferForScene(sceneObject, renderToFbo, false);
881 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "CPU buffer: Offset(%d), Cap(%d)\n", uniformBuffer1->GetCurrentOffset(), uniformBuffer1->GetCurrentCapacity());
885 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "CPU buffer: nil\n");
889 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "GPU buffer: Offset(%d), Cap(%d)\n", uniformBuffer2->GetCurrentOffset(), uniformBuffer2->GetCurrentCapacity());
893 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "GPU buffer: nil\n");
897 for(uint32_t i = 0; i < instructionCount; ++i)
899 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
901 if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
906 // Mark that we will require a post-render step to be performed (includes swap-buffers).
907 status.SetNeedsPostRender(true);
909 Rect<int32_t> viewportRect;
911 int32_t surfaceOrientation = sceneObject->GetSurfaceOrientation() + sceneObject->GetScreenOrientation();
912 if(surfaceOrientation >= 360)
914 surfaceOrientation -= 360;
917 // @todo Should these be part of scene?
918 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
919 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
921 Graphics::RenderTarget* currentRenderTarget = nullptr;
922 Graphics::RenderPass* currentRenderPass = nullptr;
923 std::vector<Graphics::ClearValue> currentClearValues{};
925 if(instruction.mFrameBuffer)
927 // Ensure graphics framebuffer is created, bind attachments and create render passes
928 // Only happens once per framebuffer. If the create fails, e.g. no attachments yet,
929 // then don't render to this framebuffer.
930 if(!instruction.mFrameBuffer->GetGraphicsObject())
932 const bool created = instruction.mFrameBuffer->CreateGraphicsObjects();
939 auto& clearValues = instruction.mFrameBuffer->GetGraphicsRenderPassClearValues();
941 // Set the clear color for first color attachment
942 if(instruction.mIsClearColorSet && !clearValues.empty())
944 clearValues[0].color = {
945 instruction.mClearColor.r,
946 instruction.mClearColor.g,
947 instruction.mClearColor.b,
948 instruction.mClearColor.a};
951 currentClearValues = clearValues;
953 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
956 currentRenderTarget = instruction.mFrameBuffer->GetGraphicsRenderTarget();
957 currentRenderPass = instruction.mFrameBuffer->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
959 else // no framebuffer
962 auto& clearValues = sceneObject->GetGraphicsRenderPassClearValues();
964 if(instruction.mIsClearColorSet)
966 clearValues[0].color = {
967 instruction.mClearColor.r,
968 instruction.mClearColor.g,
969 instruction.mClearColor.b,
970 instruction.mClearColor.a};
973 currentClearValues = clearValues;
975 // @todo SceneObject should already have the depth clear / stencil clear in the clearValues array.
976 // if the window has a depth/stencil buffer.
977 if((depthBufferAvailable == Integration::DepthBufferAvailable::TRUE ||
978 stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE) &&
979 (currentClearValues.size() <= 1))
981 currentClearValues.emplace_back();
982 currentClearValues.back().depthStencil.depth = 0;
983 currentClearValues.back().depthStencil.stencil = 0;
986 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
988 currentRenderTarget = sceneObject->GetSurfaceRenderTarget();
989 currentRenderPass = sceneObject->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
992 targetstoPresent.emplace_back(currentRenderTarget);
994 if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
996 // Offscreen buffer rendering
997 if(instruction.mIsViewportSet)
999 // For Viewport the lower-left corner is (0,0)
1000 const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
1001 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
1005 viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
1007 surfaceOrientation = 0;
1009 else // No Offscreen frame buffer rendering
1011 // Check whether a viewport is specified, otherwise the full surface size is used
1012 if(instruction.mIsViewportSet)
1014 // For Viewport the lower-left corner is (0,0)
1015 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
1016 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
1020 viewportRect = surfaceRect;
1024 // Set surface orientation
1025 // @todo Inform graphics impl by another route.
1026 // was: mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
1028 /*** Clear region of framebuffer or surface before drawing ***/
1029 bool clearFullFrameRect = (surfaceRect == viewportRect);
1030 if(instruction.mFrameBuffer != nullptr)
1032 Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
1033 clearFullFrameRect = (frameRect == viewportRect);
1036 if(!clippingRect.IsEmpty())
1038 if(!clippingRect.Intersect(viewportRect))
1040 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
1041 clippingRect = Rect<int>();
1043 clearFullFrameRect = false;
1046 Graphics::Rect2D scissorArea{viewportRect.x, viewportRect.y, uint32_t(viewportRect.width), uint32_t(viewportRect.height)};
1047 if(instruction.mIsClearColorSet)
1049 if(!clearFullFrameRect)
1051 if(!clippingRect.IsEmpty())
1053 scissorArea = {clippingRect.x, clippingRect.y, uint32_t(clippingRect.width), uint32_t(clippingRect.height)};
1058 // Scissor's value should be set based on the default system coordinates.
1059 // When the surface is rotated, the input values already were set with the rotated angle.
1060 // So, re-calculation is needed.
1061 scissorArea = RecalculateScissorArea(scissorArea, surfaceOrientation, surfaceRect);
1063 // Begin render pass
1064 mainCommandBuffer->BeginRenderPass(
1066 currentRenderTarget,
1068 currentClearValues);
1070 mainCommandBuffer->SetViewport({float(viewportRect.x),
1071 float(viewportRect.y),
1072 float(viewportRect.width),
1073 float(viewportRect.height)});
1075 mImpl->renderAlgorithms.ProcessRenderInstruction(
1077 mImpl->renderBufferIndex,
1078 depthBufferAvailable,
1079 stencilBufferAvailable,
1083 Uint16Pair(surfaceRect.width, surfaceRect.height));
1085 Graphics::SyncObject* syncObject{nullptr};
1086 // If the render instruction has an associated render tracker (owned separately)
1087 // and framebuffer, create a one shot sync object, and use it to determine when
1088 // the render pass has finished executing on GPU.
1089 if(instruction.mRenderTracker && instruction.mFrameBuffer)
1091 syncObject = instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController);
1092 instruction.mRenderTracker = nullptr;
1094 mainCommandBuffer->EndRenderPass(syncObject);
1098 mImpl->uniformBufferManager->Flush(sceneObject, renderToFbo);
1099 mImpl->renderAlgorithms.SubmitCommandBuffer();
1100 mImpl->commandBufferSubmitted = true;
1102 std::sort(targetstoPresent.begin(), targetstoPresent.end());
1104 Graphics::RenderTarget* rt = nullptr;
1105 for(auto& target : targetstoPresent)
1109 mImpl->graphicsController.PresentRenderTarget(target);
1115 void RenderManager::PostRender()
1117 if(!mImpl->commandBufferSubmitted)
1119 // Rendering is skipped but there may be pending tasks. Flush them.
1120 Graphics::SubmitInfo submitInfo;
1121 submitInfo.cmdBuffer.clear(); // Only flush
1122 submitInfo.flags = 0 | Graphics::SubmitFlagBits::FLUSH;
1123 mImpl->graphicsController.SubmitCommandBuffers(submitInfo);
1125 mImpl->commandBufferSubmitted = true;
1128 // Notify RenderGeometries that rendering has finished
1129 for(auto&& iter : mImpl->geometryContainer)
1131 iter->OnRenderFinished();
1134 // Notify updated RenderTexture that rendering has finished
1135 for(auto&& iter : mImpl->updatedTextures)
1137 iter->OnRenderFinished();
1139 mImpl->updatedTextures.Clear();
1141 // Remove discarded textures after OnRenderFinished called
1142 mImpl->textureDiscardQueue.Clear();
1144 mImpl->UpdateTrackers();
1146 uint32_t count = 0u;
1147 for(auto& scene : mImpl->sceneContainer)
1149 count += scene->GetRenderInstructions().Count(mImpl->renderBufferIndex);
1152 // Remove unused shader and programs during CACHE_CLEAN_FRAME_COUNT frames.
1153 // TODO : Cache clean logic have some problem now. Just block it until bug resolved
1155 if(mImpl->frameCount % CACHE_CLEAN_FRAME_COUNT == 0)
1157 mImpl->programController.ClearUnusedCache();
1161 const bool haveInstructions = count > 0u;
1163 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1164 mImpl->lastFrameWasRendered = haveInstructions;
1167 * The rendering has finished; swap to the next buffer.
1168 * Ideally the update has just finished using this buffer; otherwise the render thread
1169 * should block until the update has finished.
1171 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1173 DALI_PRINT_RENDER_END();
1176 } // namespace SceneGraph
1178 } // namespace Internal