2 * Copyright (c) 2021 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/render-tasks/scene-graph-camera.h>
33 #include <dali/internal/render/common/render-algorithms.h>
34 #include <dali/internal/render/common/render-debug.h>
35 #include <dali/internal/render/common/render-instruction.h>
36 #include <dali/internal/render/common/render-tracker.h>
37 #include <dali/internal/render/queue/render-queue.h>
38 #include <dali/internal/render/renderers/pipeline-cache.h>
39 #include <dali/internal/render/renderers/render-frame-buffer.h>
40 #include <dali/internal/render/renderers/render-texture.h>
41 #include <dali/internal/render/renderers/shader-cache.h>
42 #include <dali/internal/render/renderers/uniform-buffer-manager.h>
43 #include <dali/internal/render/renderers/uniform-buffer-view-pool.h>
44 #include <dali/internal/render/shaders/program-controller.h>
54 #if defined(DEBUG_ENABLED)
57 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER");
58 } // unnamed namespace
63 inline Graphics::Rect2D RecalculateScissorArea(Graphics::Rect2D scissorArea, int orientation, Rect<int32_t> viewportRect)
65 Graphics::Rect2D newScissorArea;
69 newScissorArea.x = viewportRect.height - (scissorArea.y + scissorArea.height);
70 newScissorArea.y = scissorArea.x;
71 newScissorArea.width = scissorArea.height;
72 newScissorArea.height = scissorArea.width;
74 else if(orientation == 180)
76 newScissorArea.x = viewportRect.width - (scissorArea.x + scissorArea.width);
77 newScissorArea.y = viewportRect.height - (scissorArea.y + scissorArea.height);
78 newScissorArea.width = scissorArea.width;
79 newScissorArea.height = scissorArea.height;
81 else if(orientation == 270)
83 newScissorArea.x = scissorArea.y;
84 newScissorArea.y = viewportRect.width - (scissorArea.x + scissorArea.width);
85 newScissorArea.width = scissorArea.height;
86 newScissorArea.height = scissorArea.width;
90 newScissorArea.x = scissorArea.x;
91 newScissorArea.y = scissorArea.y;
92 newScissorArea.width = scissorArea.width;
93 newScissorArea.height = scissorArea.height;
95 return newScissorArea;
99 * Structure to contain internal data
101 struct RenderManager::Impl
103 Impl(Graphics::Controller& graphicsController,
104 Integration::DepthBufferAvailable depthBufferAvailableParam,
105 Integration::StencilBufferAvailable stencilBufferAvailableParam,
106 Integration::PartialUpdateAvailable partialUpdateAvailableParam)
107 : graphicsController(graphicsController),
109 renderAlgorithms(graphicsController),
111 renderBufferIndex(SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX),
115 frameBufferContainer(),
116 lastFrameWasRendered(false),
117 programController(graphicsController),
118 shaderCache(graphicsController),
119 depthBufferAvailable(depthBufferAvailableParam),
120 stencilBufferAvailable(stencilBufferAvailableParam),
121 partialUpdateAvailable(partialUpdateAvailableParam)
123 // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
124 threadPool = std::make_unique<Dali::ThreadPool>();
125 threadPool->Initialize(1u);
127 uniformBufferManager = std::make_unique<Render::UniformBufferManager>(&graphicsController);
128 pipelineCache = std::make_unique<Render::PipelineCache>(graphicsController);
133 threadPool.reset(nullptr); // reset now to maintain correct destruction order
136 void AddRenderTracker(Render::RenderTracker* renderTracker)
138 DALI_ASSERT_DEBUG(renderTracker != nullptr);
139 mRenderTrackers.PushBack(renderTracker);
142 void RemoveRenderTracker(Render::RenderTracker* renderTracker)
144 mRenderTrackers.EraseObject(renderTracker);
147 void UpdateTrackers()
149 for(auto&& iter : mRenderTrackers)
151 iter->PollSyncObject();
155 // the order is important for destruction,
156 Graphics::Controller& graphicsController;
157 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
159 std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
161 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
163 uint32_t frameCount; ///< The current frame count
164 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
166 OwnerContainer<Render::Renderer*> rendererContainer; ///< List of owned renderers
167 OwnerContainer<Render::Sampler*> samplerContainer; ///< List of owned samplers
168 OwnerContainer<Render::Texture*> textureContainer; ///< List of owned textures
169 OwnerContainer<Render::FrameBuffer*> frameBufferContainer; ///< List of owned framebuffers
170 OwnerContainer<Render::VertexBuffer*> vertexBufferContainer; ///< List of owned vertex buffers
171 OwnerContainer<Render::Geometry*> geometryContainer; ///< List of owned Geometries
173 bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
175 OwnerContainer<Render::RenderTracker*> mRenderTrackers; ///< List of render trackers
177 ProgramController programController; ///< Owner of the programs
178 Render::ShaderCache shaderCache; ///< The cache for the graphics shaders
180 std::unique_ptr<Render::UniformBufferManager> uniformBufferManager; ///< The uniform buffer manager
181 std::unique_ptr<Render::PipelineCache> pipelineCache;
183 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
184 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
185 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
187 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
188 Vector<Graphics::Texture*> boundTextures; ///< The textures bound for rendering
189 Vector<Graphics::Texture*> textureDependencyList; ///< The dependency list of bound textures
192 RenderManager* RenderManager::New(Graphics::Controller& graphicsController,
193 Integration::DepthBufferAvailable depthBufferAvailable,
194 Integration::StencilBufferAvailable stencilBufferAvailable,
195 Integration::PartialUpdateAvailable partialUpdateAvailable)
197 auto* manager = new RenderManager;
198 manager->mImpl = new Impl(graphicsController,
199 depthBufferAvailable,
200 stencilBufferAvailable,
201 partialUpdateAvailable);
205 RenderManager::RenderManager()
210 RenderManager::~RenderManager()
215 RenderQueue& RenderManager::GetRenderQueue()
217 return mImpl->renderQueue;
220 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
224 void RenderManager::AddRenderer(OwnerPointer<Render::Renderer>& renderer)
226 // Initialize the renderer as we are now in render thread
227 renderer->Initialize(mImpl->graphicsController, mImpl->programController, mImpl->shaderCache, *(mImpl->uniformBufferManager.get()), *(mImpl->pipelineCache.get()));
229 mImpl->rendererContainer.PushBack(renderer.Release());
232 void RenderManager::RemoveRenderer(Render::Renderer* renderer)
234 mImpl->rendererContainer.EraseObject(renderer);
237 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
239 sampler->Initialize(mImpl->graphicsController);
240 mImpl->samplerContainer.PushBack(sampler.Release());
243 void RenderManager::RemoveSampler(Render::Sampler* sampler)
245 mImpl->samplerContainer.EraseObject(sampler);
248 void RenderManager::AddTexture(OwnerPointer<Render::Texture>& texture)
250 texture->Initialize(mImpl->graphicsController);
251 mImpl->textureContainer.PushBack(texture.Release());
254 void RenderManager::RemoveTexture(Render::Texture* texture)
256 DALI_ASSERT_DEBUG(NULL != texture);
258 // Find the texture, use std::find so we can do the erase safely
259 auto iter = std::find(mImpl->textureContainer.begin(), mImpl->textureContainer.end(), texture);
261 if(iter != mImpl->textureContainer.end())
264 mImpl->textureContainer.Erase(iter); // Texture found; now destroy it
268 void RenderManager::UploadTexture(Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params)
270 texture->Upload(pixelData, params);
273 void RenderManager::GenerateMipmaps(Render::Texture* texture)
275 texture->GenerateMipmaps();
278 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
280 sampler->SetFilterMode(static_cast<Dali::FilterMode::Type>(minFilterMode),
281 static_cast<Dali::FilterMode::Type>(magFilterMode));
284 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
286 sampler->SetWrapMode(static_cast<Dali::WrapMode::Type>(rWrapMode),
287 static_cast<Dali::WrapMode::Type>(sWrapMode),
288 static_cast<Dali::WrapMode::Type>(tWrapMode));
291 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
293 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
294 mImpl->frameBufferContainer.PushBack(frameBufferPtr);
295 frameBufferPtr->Initialize(mImpl->graphicsController);
298 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
300 DALI_ASSERT_DEBUG(nullptr != frameBuffer);
302 // Find the framebuffer, use std:find so we can safely do the erase
303 auto iter = std::find(mImpl->frameBufferContainer.begin(), mImpl->frameBufferContainer.end(), frameBuffer);
305 if(iter != mImpl->frameBufferContainer.end())
307 frameBuffer->Destroy();
308 mImpl->frameBufferContainer.Erase(iter); // frameBuffer found; now destroy it
312 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
314 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
315 mImpl->sceneContainer.push_back(scene);
318 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
320 auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
321 if(iter != mImpl->sceneContainer.end())
323 mImpl->sceneContainer.erase(iter);
327 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
329 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
332 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
334 frameBuffer->AttachColorTexture(texture, mipmapLevel, layer);
337 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
339 frameBuffer->AttachDepthTexture(texture, mipmapLevel);
342 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
344 frameBuffer->AttachDepthStencilTexture(texture, mipmapLevel);
347 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
349 mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
352 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
354 mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
357 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
359 vertexBuffer->SetFormat(format.Release());
362 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
364 vertexBuffer->SetData(data.Release(), size);
367 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Dali::Vector<uint16_t>& indices)
369 geometry->SetIndexBuffer(indices);
372 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
374 mImpl->geometryContainer.PushBack(geometry.Release());
377 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
379 auto iter = std::find(mImpl->geometryContainer.begin(), mImpl->geometryContainer.end(), geometry);
381 if(iter != mImpl->geometryContainer.end())
383 mImpl->geometryContainer.Erase(iter);
387 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
389 DALI_ASSERT_DEBUG(nullptr != geometry);
392 for(auto&& iter : mImpl->geometryContainer)
396 iter->AddVertexBuffer(vertexBuffer);
402 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
404 DALI_ASSERT_DEBUG(nullptr != geometry);
407 for(auto&& iter : mImpl->geometryContainer)
411 iter->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, bool uploadOnly)
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);
468 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
470 if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
475 Internal::Scene& sceneInternal = GetImplementation(scene);
476 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
478 if(sceneObject->IsRenderingSkipped())
480 // We don't need to calculate dirty rects
484 class DamagedRectsCleaner
487 explicit DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects, Rect<int>& surfaceRect)
488 : mDamagedRects(damagedRects),
489 mSurfaceRect(surfaceRect),
494 void SetCleanOnReturn(bool cleanOnReturn)
496 mCleanOnReturn = cleanOnReturn;
499 ~DamagedRectsCleaner()
503 mDamagedRects.clear();
504 mDamagedRects.push_back(mSurfaceRect);
509 std::vector<Rect<int>>& mDamagedRects;
510 Rect<int> mSurfaceRect;
514 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
516 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
517 DamagedRectsCleaner damagedRectCleaner(damagedRects, surfaceRect);
519 // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
520 // so you don't need to sort: std::stable_sort(itemsDirtyRects.begin(), itemsDirtyRects.end());
521 std::vector<DirtyRect>& itemsDirtyRects = sceneInternal.GetItemsDirtyRects();
522 for(DirtyRect& dirtyRect : itemsDirtyRects)
524 dirtyRect.visited = false;
527 uint32_t instructionCount = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
528 for(uint32_t i = 0; i < instructionCount; ++i)
530 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
532 if(instruction.mFrameBuffer)
534 return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
537 const Camera* camera = instruction.GetCamera();
538 if(camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
540 const Node* node = instruction.GetCamera()->GetNode();
545 Quaternion orientation;
546 node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
548 Vector3 orientationAxis;
549 Radian orientationAngle;
550 orientation.ToAxisAngle(orientationAxis, orientationAngle);
552 if(position.x > Math::MACHINE_EPSILON_10000 ||
553 position.y > Math::MACHINE_EPSILON_10000 ||
554 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
555 orientationAngle != ANGLE_180 ||
556 scale != Vector3(1.0f, 1.0f, 1.0f))
567 Rect<int32_t> viewportRect;
568 if(instruction.mIsViewportSet)
570 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
571 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
572 if(viewportRect.IsEmpty() || !viewportRect.IsValid())
574 return; // just skip funny use cases for now, empty viewport means it is set somewhere else
579 viewportRect = surfaceRect;
582 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
583 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
584 if(viewMatrix && projectionMatrix)
586 const RenderListContainer::SizeType count = instruction.RenderListCount();
587 for(RenderListContainer::SizeType index = 0u; index < count; ++index)
589 const RenderList* renderList = instruction.GetRenderList(index);
590 if(renderList && !renderList->IsEmpty())
592 const std::size_t listCount = renderList->Count();
593 for(uint32_t listIndex = 0u; listIndex < listCount; ++listIndex)
595 RenderItem& item = renderList->GetItem(listIndex);
596 // If the item does 3D transformation, do early exit and clean the damaged rect array
597 if(item.mUpdateSize == Vector3::ZERO)
603 DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
604 // If the item refers to updated node or renderer.
605 if(item.mIsUpdated ||
607 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
609 item.mIsUpdated = false;
610 item.mNode->SetUpdatedTree(false);
612 rect = RenderItem::CalculateViewportSpaceAABB(item.mModelViewMatrix, item.mUpdateSize, viewportRect.width, viewportRect.height);
613 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
615 const int left = rect.x;
616 const int top = rect.y;
617 const int right = rect.x + rect.width;
618 const int bottom = rect.y + rect.height;
619 rect.x = (left / 16) * 16;
620 rect.y = (top / 16) * 16;
621 rect.width = ((right + 16) / 16) * 16 - rect.x;
622 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
624 // Found valid dirty rect.
625 // 1. Insert it in the sorted array of the dirty rects.
626 // 2. Mark the related dirty rects as visited so they will not be removed below.
627 // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
628 dirtyRect.rect = rect;
629 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
630 dirtyRectPos = itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
633 while(++dirtyRectPos != itemsDirtyRects.end())
635 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
640 dirtyRectPos->visited = true;
641 Rect<int>& dirtRect = dirtyRectPos->rect;
642 rect.Merge(dirtRect);
645 if(c > 3) // no more then 3 previous rects
647 itemsDirtyRects.erase(dirtyRectPos);
652 damagedRects.push_back(rect);
657 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
658 // 2. Mark the related dirty rects as visited so they will not be removed below.
659 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
660 while(dirtyRectPos != itemsDirtyRects.end())
662 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
667 dirtyRectPos->visited = true;
677 // Check removed nodes or removed renderers dirty rects
678 auto i = itemsDirtyRects.begin();
679 auto j = itemsDirtyRects.begin();
680 while(i != itemsDirtyRects.end())
688 Rect<int>& dirtRect = i->rect;
689 damagedRects.push_back(dirtRect);
694 itemsDirtyRects.resize(j - itemsDirtyRects.begin());
695 damagedRectCleaner.SetCleanOnReturn(false);
698 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
700 Rect<int> clippingRect;
701 RenderScene(status, scene, renderToFbo, clippingRect);
704 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
706 if(mImpl->partialUpdateAvailable == Integration::PartialUpdateAvailable::TRUE && !renderToFbo && clippingRect.IsEmpty())
708 // ClippingRect is empty. Skip rendering
712 // Reset main algorithms command buffer
713 mImpl->renderAlgorithms.ResetCommandBuffer();
715 auto mainCommandBuffer = mImpl->renderAlgorithms.GetMainCommandBuffer();
717 Internal::Scene& sceneInternal = GetImplementation(scene);
718 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
720 uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
722 std::vector<Graphics::RenderTarget*> targetstoPresent;
724 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
725 if(clippingRect == surfaceRect)
727 // Full rendering case
728 // Make clippingRect empty because we're doing full rendering now if the clippingRect is empty.
729 // To reduce side effects, keep this logic now.
730 clippingRect = Rect<int>();
733 for(uint32_t i = 0; i < count; ++i)
735 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
737 if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
742 // Mark that we will require a post-render step to be performed (includes swap-buffers).
743 status.SetNeedsPostRender(true);
745 Rect<int32_t> viewportRect;
747 int32_t surfaceOrientation = sceneObject->GetSurfaceOrientation();
749 // @todo Should these be part of scene?
750 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
751 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
753 Graphics::RenderTarget* currentRenderTarget = nullptr;
754 Graphics::RenderPass* currentRenderPass = nullptr;
755 std::vector<Graphics::ClearValue> currentClearValues{};
757 if(instruction.mFrameBuffer)
759 // Ensure graphics framebuffer is created, bind attachments and create render passes
760 // Only happens once per framebuffer. If the create fails, e.g. no attachments yet,
761 // then don't render to this framebuffer.
762 if(!instruction.mFrameBuffer->GetGraphicsObject())
764 const bool created = instruction.mFrameBuffer->CreateGraphicsObjects();
771 auto& clearValues = instruction.mFrameBuffer->GetGraphicsRenderPassClearValues();
773 // Set the clear color for first color attachment
774 if(instruction.mIsClearColorSet && !clearValues.empty())
776 clearValues[0].color = {
777 instruction.mClearColor.r,
778 instruction.mClearColor.g,
779 instruction.mClearColor.b,
780 instruction.mClearColor.a};
783 currentClearValues = clearValues;
785 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
788 currentRenderTarget = instruction.mFrameBuffer->GetGraphicsRenderTarget();
789 currentRenderPass = instruction.mFrameBuffer->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
791 else // no framebuffer
794 auto& clearValues = sceneObject->GetGraphicsRenderPassClearValues();
796 if(instruction.mIsClearColorSet)
798 clearValues[0].color = {
799 instruction.mClearColor.r,
800 instruction.mClearColor.g,
801 instruction.mClearColor.b,
802 instruction.mClearColor.a};
805 currentClearValues = clearValues;
807 // @todo SceneObject should already have the depth clear / stencil clear in the clearValues array.
808 // if the window has a depth/stencil buffer.
809 if((depthBufferAvailable == Integration::DepthBufferAvailable::TRUE ||
810 stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE) &&
811 (currentClearValues.size() <= 1))
813 currentClearValues.emplace_back();
814 currentClearValues.back().depthStencil.depth = 0;
815 currentClearValues.back().depthStencil.stencil = 0;
818 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
820 currentRenderTarget = sceneObject->GetSurfaceRenderTarget();
821 currentRenderPass = sceneObject->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
824 targetstoPresent.emplace_back(currentRenderTarget);
826 // reset the program matrices for all programs once per frame
827 // this ensures we will set view and projection matrix once per program per camera
828 mImpl->programController.ResetProgramMatrices();
830 if(instruction.mFrameBuffer)
832 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
833 for(unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
835 mImpl->textureDependencyList.PushBack(instruction.mFrameBuffer->GetTexture(i0));
839 if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
841 // Offscreen buffer rendering
842 if(instruction.mIsViewportSet)
844 // For Viewport the lower-left corner is (0,0)
845 const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
846 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
850 viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
852 surfaceOrientation = 0;
854 else // No Offscreen frame buffer rendering
856 // Check whether a viewport is specified, otherwise the full surface size is used
857 if(instruction.mIsViewportSet)
859 // For Viewport the lower-left corner is (0,0)
860 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
861 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
865 viewportRect = surfaceRect;
869 // Set surface orientation
870 // @todo Inform graphics impl by another route.
871 // was: mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
873 /*** Clear region of framebuffer or surface before drawing ***/
874 bool clearFullFrameRect = (surfaceRect == viewportRect);
875 if(instruction.mFrameBuffer != nullptr)
877 Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
878 clearFullFrameRect = (frameRect == viewportRect);
881 if(!clippingRect.IsEmpty())
883 if(!clippingRect.Intersect(viewportRect))
885 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
886 clippingRect = Rect<int>();
888 clearFullFrameRect = false;
891 Graphics::Rect2D scissorArea{viewportRect.x, viewportRect.y, uint32_t(viewportRect.width), uint32_t(viewportRect.height)};
892 if(instruction.mIsClearColorSet)
894 if(!clearFullFrameRect)
896 if(!clippingRect.IsEmpty())
898 scissorArea = {clippingRect.x, clippingRect.y, uint32_t(clippingRect.width), uint32_t(clippingRect.height)};
903 // Scissor's value should be set based on the default system coordinates.
904 // When the surface is rotated, the input values already were set with the rotated angle.
905 // So, re-calculation is needed.
906 scissorArea = RecalculateScissorArea(scissorArea, surfaceOrientation, viewportRect);
909 mainCommandBuffer->BeginRenderPass(
915 mainCommandBuffer->SetViewport({float(viewportRect.x),
916 float(viewportRect.y),
917 float(viewportRect.width),
918 float(viewportRect.height)});
920 // Clear the list of bound textures
921 mImpl->boundTextures.Clear();
923 mImpl->renderAlgorithms.ProcessRenderInstruction(
925 mImpl->renderBufferIndex,
926 depthBufferAvailable,
927 stencilBufferAvailable,
928 mImpl->boundTextures,
933 Graphics::SyncObject* syncObject{nullptr};
934 // If the render instruction has an associated render tracker (owned separately)
935 // and framebuffer, create a one shot sync object, and use it to determine when
936 // the render pass has finished executing on GPU.
937 if(instruction.mRenderTracker && instruction.mFrameBuffer)
939 syncObject = instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController);
940 instruction.mRenderTracker = nullptr;
942 mainCommandBuffer->EndRenderPass(syncObject);
944 mImpl->renderAlgorithms.SubmitCommandBuffer();
946 std::sort(targetstoPresent.begin(), targetstoPresent.end());
948 Graphics::RenderTarget* rt = nullptr;
949 for(auto& target : targetstoPresent)
953 mImpl->graphicsController.PresentRenderTarget(target);
959 void RenderManager::PostRender(bool uploadOnly)
961 // Notify RenderGeometries that rendering has finished
962 for(auto&& iter : mImpl->geometryContainer)
964 iter->OnRenderFinished();
967 mImpl->UpdateTrackers();
970 for(auto& scene : mImpl->sceneContainer)
972 count += scene->GetRenderInstructions().Count(mImpl->renderBufferIndex);
975 const bool haveInstructions = count > 0u;
977 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
978 mImpl->lastFrameWasRendered = haveInstructions;
981 * The rendering has finished; swap to the next buffer.
982 * Ideally the update has just finished using this buffer; otherwise the render thread
983 * should block until the update has finished.
985 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
987 DALI_PRINT_RENDER_END();
990 } // namespace SceneGraph
992 } // namespace Internal