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>
27 #include <dali/integration-api/gl-context-helper-abstraction.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/render-tasks/scene-graph-camera.h>
34 #include <dali/internal/render/common/render-algorithms.h>
35 #include <dali/internal/render/common/render-debug.h>
36 #include <dali/internal/render/common/render-instruction.h>
37 #include <dali/internal/render/common/render-tracker.h>
38 #include <dali/internal/render/queue/render-queue.h>
39 #include <dali/internal/render/renderers/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/shaders/program-controller.h>
51 #if defined(DEBUG_ENABLED)
54 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER");
55 } // unnamed namespace
59 * Structure to contain internal data
61 struct RenderManager::Impl
63 Impl(Graphics::Controller& graphicsController,
64 Integration::DepthBufferAvailable depthBufferAvailableParam,
65 Integration::StencilBufferAvailable stencilBufferAvailableParam,
66 Integration::PartialUpdateAvailable partialUpdateAvailableParam)
67 : graphicsController(graphicsController),
69 renderAlgorithms(graphicsController),
71 renderBufferIndex(SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX),
75 frameBufferContainer(),
76 lastFrameWasRendered(false),
77 programController(graphicsController),
78 shaderCache(graphicsController),
79 depthBufferAvailable(depthBufferAvailableParam),
80 stencilBufferAvailable(stencilBufferAvailableParam),
81 partialUpdateAvailable(partialUpdateAvailableParam)
83 // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
84 threadPool = std::unique_ptr<Dali::ThreadPool>(new Dali::ThreadPool());
85 threadPool->Initialize(1u);
87 uniformBufferManager.reset(new Render::UniformBufferManager(&graphicsController));
92 threadPool.reset(nullptr); // reset now to maintain correct destruction order
95 void AddRenderTracker(Render::RenderTracker* renderTracker)
97 DALI_ASSERT_DEBUG(renderTracker != nullptr);
98 mRenderTrackers.PushBack(renderTracker);
101 void RemoveRenderTracker(Render::RenderTracker* renderTracker)
103 mRenderTrackers.EraseObject(renderTracker);
106 void UpdateTrackers()
108 for(auto&& iter : mRenderTrackers)
110 iter->PollSyncObject();
114 // the order is important for destruction,
115 Graphics::Controller& graphicsController;
116 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
118 std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
120 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
122 uint32_t frameCount; ///< The current frame count
123 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
125 OwnerContainer<Render::Renderer*> rendererContainer; ///< List of owned renderers
126 OwnerContainer<Render::Sampler*> samplerContainer; ///< List of owned samplers
127 OwnerContainer<Render::Texture*> textureContainer; ///< List of owned textures
128 OwnerContainer<Render::FrameBuffer*> frameBufferContainer; ///< List of owned framebuffers
129 OwnerContainer<Render::VertexBuffer*> vertexBufferContainer; ///< List of owned vertex buffers
130 OwnerContainer<Render::Geometry*> geometryContainer; ///< List of owned Geometries
132 bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
134 OwnerContainer<Render::RenderTracker*> mRenderTrackers; ///< List of render trackers
136 ProgramController programController; ///< Owner of the GL programs
137 Render::ShaderCache shaderCache; ///< The cache for the graphics shaders
139 std::unique_ptr<Render::UniformBufferManager> uniformBufferManager; ///< The uniform buffer manager
141 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
142 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
143 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
145 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
146 Vector<Graphics::Texture*> boundTextures; ///< The textures bound for rendering
147 Vector<Graphics::Texture*> textureDependencyList; ///< The dependency list of bound textures
150 RenderManager* RenderManager::New(Graphics::Controller& graphicsController,
151 Integration::DepthBufferAvailable depthBufferAvailable,
152 Integration::StencilBufferAvailable stencilBufferAvailable,
153 Integration::PartialUpdateAvailable partialUpdateAvailable)
155 auto* manager = new RenderManager;
156 manager->mImpl = new Impl(graphicsController,
157 depthBufferAvailable,
158 stencilBufferAvailable,
159 partialUpdateAvailable);
163 RenderManager::RenderManager()
168 RenderManager::~RenderManager()
173 RenderQueue& RenderManager::GetRenderQueue()
175 return mImpl->renderQueue;
178 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
182 void RenderManager::AddRenderer(OwnerPointer<Render::Renderer>& renderer)
184 // Initialize the renderer as we are now in render thread
185 renderer->Initialize(mImpl->graphicsController, mImpl->programController, mImpl->shaderCache, *(mImpl->uniformBufferManager.get()));
187 mImpl->rendererContainer.PushBack(renderer.Release());
190 void RenderManager::RemoveRenderer(Render::Renderer* renderer)
192 mImpl->rendererContainer.EraseObject(renderer);
195 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
197 sampler->Initialize(mImpl->graphicsController);
198 mImpl->samplerContainer.PushBack(sampler.Release());
201 void RenderManager::RemoveSampler(Render::Sampler* sampler)
203 mImpl->samplerContainer.EraseObject(sampler);
206 void RenderManager::AddTexture(OwnerPointer<Render::Texture>& texture)
208 texture->Initialize(mImpl->graphicsController);
209 mImpl->textureContainer.PushBack(texture.Release());
212 void RenderManager::RemoveTexture(Render::Texture* texture)
214 DALI_ASSERT_DEBUG(NULL != texture);
216 // Find the texture, use reference to pointer so we can do the erase safely
217 for(auto&& iter : mImpl->textureContainer)
222 mImpl->textureContainer.Erase(&iter); // Texture found; now destroy it
228 void RenderManager::UploadTexture(Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params)
230 texture->Upload(pixelData, params);
233 void RenderManager::GenerateMipmaps(Render::Texture* texture)
235 texture->GenerateMipmaps();
238 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
240 sampler->SetFilterMode(static_cast<Dali::FilterMode::Type>(minFilterMode),
241 static_cast<Dali::FilterMode::Type>(magFilterMode));
244 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
246 sampler->SetWrapMode(static_cast<Dali::WrapMode::Type>(rWrapMode),
247 static_cast<Dali::WrapMode::Type>(sWrapMode),
248 static_cast<Dali::WrapMode::Type>(tWrapMode));
251 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
253 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
254 mImpl->frameBufferContainer.PushBack(frameBufferPtr);
255 frameBufferPtr->Initialize(mImpl->graphicsController);
258 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
260 DALI_ASSERT_DEBUG(nullptr != frameBuffer);
262 // Find the sampler, use reference so we can safely do the erase
263 for(auto&& iter : mImpl->frameBufferContainer)
265 if(iter == frameBuffer)
267 frameBuffer->Destroy();
268 mImpl->frameBufferContainer.Erase(&iter); // frameBuffer found; now destroy it
275 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
277 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
278 mImpl->sceneContainer.push_back(scene);
281 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
283 auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
284 if(iter != mImpl->sceneContainer.end())
286 mImpl->sceneContainer.erase(iter);
290 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
292 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
295 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
297 frameBuffer->AttachColorTexture(texture, mipmapLevel, layer);
300 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
302 frameBuffer->AttachDepthTexture(texture, mipmapLevel);
305 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
307 frameBuffer->AttachDepthStencilTexture(texture, mipmapLevel);
310 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
312 mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
315 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
317 mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
320 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
322 vertexBuffer->SetFormat(format.Release());
325 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
327 vertexBuffer->SetData(data.Release(), size);
330 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Dali::Vector<uint16_t>& indices)
332 geometry->SetIndexBuffer(indices);
335 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
337 mImpl->geometryContainer.PushBack(geometry.Release());
340 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
342 mImpl->geometryContainer.EraseObject(geometry);
345 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
347 DALI_ASSERT_DEBUG(nullptr != geometry);
350 for(auto&& iter : mImpl->geometryContainer)
354 iter->AddVertexBuffer(vertexBuffer);
360 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
362 DALI_ASSERT_DEBUG(nullptr != geometry);
365 for(auto&& iter : mImpl->geometryContainer)
369 iter->RemoveVertexBuffer(vertexBuffer);
375 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
377 geometry->SetType(Render::Geometry::Type(geometryType));
380 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
382 mImpl->AddRenderTracker(renderTracker);
385 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
387 mImpl->RemoveRenderTracker(renderTracker);
390 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear, bool uploadOnly)
392 DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
394 // Increment the frame count at the beginning of each frame
397 // Process messages queued during previous update
398 mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
401 for(auto& i : mImpl->sceneContainer)
403 count += i->GetRenderInstructions().Count(mImpl->renderBufferIndex);
406 const bool haveInstructions = count > 0u;
408 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");
410 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
411 if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
413 DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
415 // Upload the geometries
416 for(auto& i : mImpl->sceneContainer)
418 RenderInstructionContainer& instructions = i->GetRenderInstructions();
419 for(uint32_t j = 0; j < instructions.Count(mImpl->renderBufferIndex); ++j)
421 RenderInstruction& instruction = instructions.At(mImpl->renderBufferIndex, j);
423 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
424 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
426 DALI_ASSERT_DEBUG(viewMatrix);
427 DALI_ASSERT_DEBUG(projectionMatrix);
429 if(viewMatrix && projectionMatrix)
431 const RenderListContainer::SizeType renderListCount = instruction.RenderListCount();
433 // Iterate through each render list.
434 for(RenderListContainer::SizeType index = 0; index < renderListCount; ++index)
436 const RenderList* renderList = instruction.GetRenderList(index);
438 if(renderList && !renderList->IsEmpty())
440 const std::size_t itemCount = renderList->Count();
441 for(uint32_t itemIndex = 0u; itemIndex < itemCount; ++itemIndex)
443 const RenderItem& item = renderList->GetItem(itemIndex);
444 if(DALI_LIKELY(item.mRenderer))
446 item.mRenderer->Upload();
457 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
459 if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
464 Internal::Scene& sceneInternal = GetImplementation(scene);
465 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
467 if(sceneObject->IsRenderingSkipped())
469 // We don't need to calculate dirty rects
473 class DamagedRectsCleaner
476 explicit DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects)
477 : mDamagedRects(damagedRects),
482 void SetCleanOnReturn(bool cleanOnReturn)
484 mCleanOnReturn = cleanOnReturn;
487 ~DamagedRectsCleaner()
491 mDamagedRects.clear();
496 std::vector<Rect<int>>& mDamagedRects;
500 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
502 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
503 DamagedRectsCleaner damagedRectCleaner(damagedRects);
505 // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
506 // so you don't need to sort: std::stable_sort(itemsDirtyRects.begin(), itemsDirtyRects.end());
507 std::vector<DirtyRect>& itemsDirtyRects = sceneInternal.GetItemsDirtyRects();
508 for(DirtyRect& dirtyRect : itemsDirtyRects)
510 dirtyRect.visited = false;
513 uint32_t instructionCount = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
514 for(uint32_t i = 0; i < instructionCount; ++i)
516 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
518 if(instruction.mFrameBuffer)
520 return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
523 const Camera* camera = instruction.GetCamera();
524 if(camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
526 const Node* node = instruction.GetCamera()->GetNode();
531 Quaternion orientation;
532 node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
534 Vector3 orientationAxis;
535 Radian orientationAngle;
536 orientation.ToAxisAngle(orientationAxis, orientationAngle);
538 if(position.x > Math::MACHINE_EPSILON_10000 ||
539 position.y > Math::MACHINE_EPSILON_10000 ||
540 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
541 orientationAngle != ANGLE_180 ||
542 scale != Vector3(1.0f, 1.0f, 1.0f))
553 Rect<int32_t> viewportRect;
554 if(instruction.mIsViewportSet)
556 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
557 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
558 if(viewportRect.IsEmpty() || !viewportRect.IsValid())
560 return; // just skip funny use cases for now, empty viewport means it is set somewhere else
565 viewportRect = surfaceRect;
568 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
569 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
570 if(viewMatrix && projectionMatrix)
572 const RenderListContainer::SizeType count = instruction.RenderListCount();
573 for(RenderListContainer::SizeType index = 0u; index < count; ++index)
575 const RenderList* renderList = instruction.GetRenderList(index);
576 if(renderList && !renderList->IsEmpty())
578 const std::size_t listCount = renderList->Count();
579 for(uint32_t listIndex = 0u; listIndex < listCount; ++listIndex)
581 RenderItem& item = renderList->GetItem(listIndex);
582 // If the item does 3D transformation, do early exit and clean the damaged rect array
583 if(item.mUpdateSize == Vector3::ZERO)
589 DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
590 // If the item refers to updated node or renderer.
591 if(item.mIsUpdated ||
593 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
595 item.mIsUpdated = false;
596 item.mNode->SetUpdated(false);
598 rect = item.CalculateViewportSpaceAABB(item.mUpdateSize, viewportRect.width, viewportRect.height);
599 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
601 const int left = rect.x;
602 const int top = rect.y;
603 const int right = rect.x + rect.width;
604 const int bottom = rect.y + rect.height;
605 rect.x = (left / 16) * 16;
606 rect.y = (top / 16) * 16;
607 rect.width = ((right + 16) / 16) * 16 - rect.x;
608 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
610 // Found valid dirty rect.
611 // 1. Insert it in the sorted array of the dirty rects.
612 // 2. Mark the related dirty rects as visited so they will not be removed below.
613 // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
614 dirtyRect.rect = rect;
615 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
616 dirtyRectPos = itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
619 while(++dirtyRectPos != itemsDirtyRects.end())
621 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
626 dirtyRectPos->visited = true;
627 Rect<int>& dirtRect = dirtyRectPos->rect;
628 rect.Merge(dirtRect);
631 if(c > 3) // no more then 3 previous rects
633 itemsDirtyRects.erase(dirtyRectPos);
638 damagedRects.push_back(rect);
643 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
644 // 2. Mark the related dirty rects as visited so they will not be removed below.
645 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
646 while(dirtyRectPos != itemsDirtyRects.end())
648 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
653 dirtyRectPos->visited = true;
663 // Check removed nodes or removed renderers dirty rects
664 auto i = itemsDirtyRects.begin();
665 auto j = itemsDirtyRects.begin();
666 while(i != itemsDirtyRects.end())
674 Rect<int>& dirtRect = i->rect;
675 damagedRects.push_back(dirtRect);
680 itemsDirtyRects.resize(j - itemsDirtyRects.begin());
681 damagedRectCleaner.SetCleanOnReturn(false);
684 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
686 Rect<int> clippingRect;
687 RenderScene(status, scene, renderToFbo, clippingRect);
690 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
692 // Reset main algorithms command buffer
693 mImpl->renderAlgorithms.ResetCommandBuffer();
695 auto mainCommandBuffer = mImpl->renderAlgorithms.GetMainCommandBuffer();
697 Internal::Scene& sceneInternal = GetImplementation(scene);
698 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
700 uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
702 std::vector<Graphics::RenderTarget*> targetstoPresent;
704 for(uint32_t i = 0; i < count; ++i)
706 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
708 if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
713 // Mark that we will require a post-render step to be performed (includes swap-buffers).
714 status.SetNeedsPostRender(true);
716 Rect<int32_t> viewportRect;
718 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
719 int32_t surfaceOrientation = sceneObject->GetSurfaceOrientation();
721 // @todo Should these be part of scene?
722 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
723 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
725 Graphics::RenderTarget* currentRenderTarget = nullptr;
726 Graphics::RenderPass* currentRenderPass = nullptr;
727 std::vector<Graphics::ClearValue> currentClearValues{};
729 if(instruction.mFrameBuffer)
731 // Ensure graphics framebuffer is created, bind attachments and create render passes
732 // Only happens once per framebuffer. If the create fails, e.g. no attachments yet,
733 // then don't render to this framebuffer.
734 if(!instruction.mFrameBuffer->GetGraphicsObject())
736 const bool created = instruction.mFrameBuffer->CreateGraphicsObjects();
743 auto& clearValues = instruction.mFrameBuffer->GetGraphicsRenderPassClearValues();
745 // Set the clear color for first color attachment
746 if(instruction.mIsClearColorSet && !clearValues.empty())
748 clearValues[0].color = {
749 instruction.mClearColor.r,
750 instruction.mClearColor.g,
751 instruction.mClearColor.b,
752 instruction.mClearColor.a};
755 currentClearValues = clearValues;
757 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
760 currentRenderTarget = instruction.mFrameBuffer->GetGraphicsRenderTarget();
761 currentRenderPass = instruction.mFrameBuffer->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
763 else // no framebuffer
766 auto& clearValues = sceneObject->GetGraphicsRenderPassClearValues();
768 if(instruction.mIsClearColorSet)
770 clearValues[0].color = {
771 instruction.mClearColor.r,
772 instruction.mClearColor.g,
773 instruction.mClearColor.b,
774 instruction.mClearColor.a};
777 currentClearValues = clearValues;
779 // @todo SceneObject should already have the depth clear / stencil clear in the clearValues array.
780 // if the window has a depth/stencil buffer.
781 if((depthBufferAvailable == Integration::DepthBufferAvailable::TRUE ||
782 stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE) &&
783 (currentClearValues.size() <= 1))
785 currentClearValues.emplace_back();
786 currentClearValues.back().depthStencil.depth = 0;
787 currentClearValues.back().depthStencil.stencil = 0;
790 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
792 currentRenderTarget = sceneObject->GetSurfaceRenderTarget();
793 currentRenderPass = sceneObject->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
796 targetstoPresent.emplace_back(currentRenderTarget);
798 // reset the program matrices for all programs once per frame
799 // this ensures we will set view and projection matrix once per program per camera
800 mImpl->programController.ResetProgramMatrices();
802 if(instruction.mFrameBuffer)
804 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
805 for(unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
807 mImpl->textureDependencyList.PushBack(instruction.mFrameBuffer->GetTexture(i0));
811 if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
813 // Offscreen buffer rendering
814 if(instruction.mIsViewportSet)
816 // For glViewport the lower-left corner is (0,0)
817 const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
818 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
822 viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
824 surfaceOrientation = 0;
826 else // No Offscreen frame buffer rendering
828 // Check whether a viewport is specified, otherwise the full surface size is used
829 if(instruction.mIsViewportSet)
831 // For glViewport the lower-left corner is (0,0)
832 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
833 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
837 viewportRect = surfaceRect;
841 // Set surface orientation
842 // @todo Inform graphics impl by another route.
843 // was: mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
845 /*** Clear region of framebuffer or surface before drawing ***/
846 bool clearFullFrameRect = (surfaceRect == viewportRect);
847 if(instruction.mFrameBuffer != nullptr)
849 Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
850 clearFullFrameRect = (frameRect == viewportRect);
853 if(!clippingRect.IsEmpty())
855 if(!clippingRect.Intersect(viewportRect))
857 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
858 clippingRect = Rect<int>();
860 clearFullFrameRect = false;
863 Graphics::Rect2D scissorArea{viewportRect.x, viewportRect.y, uint32_t(viewportRect.width), uint32_t(viewportRect.height)};
864 if(instruction.mIsClearColorSet)
866 if(!clearFullFrameRect)
868 if(!clippingRect.IsEmpty())
870 scissorArea = {clippingRect.x, clippingRect.y, uint32_t(clippingRect.width), uint32_t(clippingRect.height)};
876 mainCommandBuffer->BeginRenderPass(
882 mainCommandBuffer->SetViewport({float(viewportRect.x),
883 float(viewportRect.y),
884 float(viewportRect.width),
885 float(viewportRect.height)});
887 // Clear the list of bound textures
888 mImpl->boundTextures.Clear();
890 mImpl->renderAlgorithms.ProcessRenderInstruction(
892 mImpl->renderBufferIndex,
893 depthBufferAvailable,
894 stencilBufferAvailable,
895 mImpl->boundTextures,
900 // Synchronise the FBO/Texture access
902 // Check whether any bound texture is in the dependency list
903 bool textureFound = false;
905 if(mImpl->boundTextures.Count() > 0u && mImpl->textureDependencyList.Count() > 0u)
907 for(auto texture : mImpl->textureDependencyList)
909 textureFound = std::find_if(mImpl->boundTextures.Begin(), mImpl->boundTextures.End(), [texture](Graphics::Texture* graphicsTexture) {
910 return texture == graphicsTexture;
911 }) != mImpl->boundTextures.End();
917 if(instruction.mFrameBuffer)
919 // For off-screen buffer
921 // Clear the dependency list
922 mImpl->textureDependencyList.Clear();
926 // Worker thread lambda function
927 auto& glContextHelperAbstraction = mImpl->graphicsController.GetGlContextHelperAbstraction();
928 auto workerFunction = [&glContextHelperAbstraction](int workerThread) {
929 // Switch to the shared context in the worker thread
930 glContextHelperAbstraction.MakeSurfacelessContextCurrent();
932 // Wait until all rendering calls for the shared context are executed
933 glContextHelperAbstraction.WaitClient();
935 // Must clear the context in the worker thread
936 // Otherwise the shared context cannot be switched to from the render thread
937 glContextHelperAbstraction.MakeContextNull();
940 auto future = mImpl->threadPool->SubmitTask(0u, workerFunction);
943 mImpl->threadPool->Wait();
945 // Clear the dependency list
946 mImpl->textureDependencyList.Clear();
951 if(instruction.mRenderTracker && instruction.mFrameBuffer)
953 // This will create a sync object every frame this render tracker
954 // is alive (though it should be now be created only for
955 // render-once render tasks)
956 // @todo Add syncing to Graphics API
957 instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController.GetGlSyncAbstraction());
958 instruction.mRenderTracker = nullptr; // Only create once.
962 mainCommandBuffer->EndRenderPass();
964 mImpl->renderAlgorithms.SubmitCommandBuffer();
966 std::sort(targetstoPresent.begin(), targetstoPresent.end());
968 Graphics::RenderTarget* rt = nullptr;
969 for(auto& target : targetstoPresent)
973 mImpl->graphicsController.PresentRenderTarget(target);
979 void RenderManager::PostRender(bool uploadOnly)
981 // Notify RenderGeometries that rendering has finished
982 for(auto&& iter : mImpl->geometryContainer)
984 iter->OnRenderFinished();
987 mImpl->UpdateTrackers();
990 for(auto& scene : mImpl->sceneContainer)
992 count += scene->GetRenderInstructions().Count(mImpl->renderBufferIndex);
995 const bool haveInstructions = count > 0u;
997 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
998 mImpl->lastFrameWasRendered = haveInstructions;
1001 * The rendering has finished; swap to the next buffer.
1002 * Ideally the update has just finished using this buffer; otherwise the render thread
1003 * should block until the update has finished.
1005 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1007 DALI_PRINT_RENDER_END();
1010 } // namespace SceneGraph
1012 } // namespace Internal