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/shaders/program-controller.h>
49 #if defined(DEBUG_ENABLED)
52 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER");
53 } // unnamed namespace
57 * Structure to contain internal data
59 struct RenderManager::Impl
61 Impl(Graphics::Controller& graphicsController,
62 Integration::DepthBufferAvailable depthBufferAvailableParam,
63 Integration::StencilBufferAvailable stencilBufferAvailableParam,
64 Integration::PartialUpdateAvailable partialUpdateAvailableParam)
65 : context(graphicsController.GetGlAbstraction(), &sceneContextContainer),
66 currentContext(&context),
67 graphicsController(graphicsController),
71 renderBufferIndex(SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX),
75 frameBufferContainer(),
76 lastFrameWasRendered(false),
77 programController(graphicsController),
78 depthBufferAvailable(depthBufferAvailableParam),
79 stencilBufferAvailable(stencilBufferAvailableParam),
80 partialUpdateAvailable(partialUpdateAvailableParam)
82 // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
83 threadPool = std::unique_ptr<Dali::ThreadPool>(new Dali::ThreadPool());
84 threadPool->Initialize(1u);
89 threadPool.reset(nullptr); // reset now to maintain correct destruction order
92 void AddRenderTracker(Render::RenderTracker* renderTracker)
94 DALI_ASSERT_DEBUG(renderTracker != NULL);
95 mRenderTrackers.PushBack(renderTracker);
98 void RemoveRenderTracker(Render::RenderTracker* renderTracker)
100 mRenderTrackers.EraseObject(renderTracker);
103 Context* CreateSceneContext()
105 Context* context = new Context(graphicsController.GetGlAbstraction());
106 sceneContextContainer.PushBack(context);
110 void DestroySceneContext(Context* sceneContext)
112 auto iter = std::find(sceneContextContainer.Begin(), sceneContextContainer.End(), sceneContext);
113 if(iter != sceneContextContainer.End())
115 (*iter)->GlContextDestroyed();
116 sceneContextContainer.Erase(iter);
120 Context* ReplaceSceneContext(Context* oldSceneContext)
122 Context* newContext = new Context(graphicsController.GetGlAbstraction());
124 oldSceneContext->GlContextDestroyed();
126 std::replace(sceneContextContainer.begin(), sceneContextContainer.end(), oldSceneContext, newContext);
130 void UpdateTrackers()
132 for(auto&& iter : mRenderTrackers)
134 iter->PollSyncObject();
138 // the order is important for destruction,
139 // programs are owned by context at the moment.
140 Context context; ///< Holds the GL state of the share resource context
141 Context* currentContext; ///< Holds the GL state of the current context for rendering
142 OwnerContainer<Context*> sceneContextContainer; ///< List of owned contexts holding the GL state per scene
143 Graphics::Controller& graphicsController;
144 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
146 std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
148 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
150 uint32_t frameCount; ///< The current frame count
151 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
153 OwnerContainer<Render::Renderer*> rendererContainer; ///< List of owned renderers
154 OwnerContainer<Render::Sampler*> samplerContainer; ///< List of owned samplers
155 OwnerContainer<Render::Texture*> textureContainer; ///< List of owned textures
156 OwnerContainer<Render::FrameBuffer*> frameBufferContainer; ///< List of owned framebuffers
157 OwnerContainer<Render::VertexBuffer*> vertexBufferContainer; ///< List of owned vertex buffers
158 OwnerContainer<Render::Geometry*> geometryContainer; ///< List of owned Geometries
160 bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
162 OwnerContainer<Render::RenderTracker*> mRenderTrackers; ///< List of render trackers
164 ProgramController programController; ///< Owner of the GL programs
166 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
167 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
168 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
170 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
171 Vector<Graphics::Texture*> boundTextures; ///< The textures bound for rendering
172 Vector<Graphics::Texture*> textureDependencyList; ///< The dependency list of binded textures
175 RenderManager* RenderManager::New(Graphics::Controller& graphicsController,
176 Integration::DepthBufferAvailable depthBufferAvailable,
177 Integration::StencilBufferAvailable stencilBufferAvailable,
178 Integration::PartialUpdateAvailable partialUpdateAvailable)
180 RenderManager* manager = new RenderManager;
181 manager->mImpl = new Impl(graphicsController,
182 depthBufferAvailable,
183 stencilBufferAvailable,
184 partialUpdateAvailable);
188 RenderManager::RenderManager()
193 RenderManager::~RenderManager()
198 RenderQueue& RenderManager::GetRenderQueue()
200 return mImpl->renderQueue;
203 void RenderManager::ContextCreated()
205 mImpl->context.GlContextCreated();
206 mImpl->programController.GlContextCreated();
208 // renderers, textures and gpu buffers cannot reinitialize themselves
209 // so they rely on someone reloading the data for them
212 void RenderManager::ContextDestroyed()
214 mImpl->context.GlContextDestroyed();
215 mImpl->programController.GlContextDestroyed();
218 for(auto&& texture : mImpl->textureContainer)
223 //Inform framebuffers
224 for(auto&& framebuffer : mImpl->frameBufferContainer)
226 framebuffer->GlContextDestroyed();
230 for(auto&& renderer : mImpl->rendererContainer)
232 renderer->GlContextDestroyed();
236 for(auto&& context : mImpl->sceneContextContainer)
238 context->GlContextDestroyed();
242 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
244 mImpl->programController.SetShaderSaver(upstream);
247 void RenderManager::AddRenderer(OwnerPointer<Render::Renderer>& renderer)
249 // Initialize the renderer as we are now in render thread
250 renderer->Initialize(mImpl->context, mImpl->graphicsController, mImpl->programController);
252 mImpl->rendererContainer.PushBack(renderer.Release());
255 void RenderManager::RemoveRenderer(Render::Renderer* renderer)
257 mImpl->rendererContainer.EraseObject(renderer);
260 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
262 sampler->Initialize(mImpl->graphicsController);
263 mImpl->samplerContainer.PushBack(sampler.Release());
266 void RenderManager::RemoveSampler(Render::Sampler* sampler)
268 mImpl->samplerContainer.EraseObject(sampler);
271 void RenderManager::AddTexture(OwnerPointer<Render::Texture>& texture)
273 texture->Initialize(mImpl->graphicsController);
274 mImpl->textureContainer.PushBack(texture.Release());
277 void RenderManager::RemoveTexture(Render::Texture* texture)
279 DALI_ASSERT_DEBUG(NULL != texture);
281 // Find the texture, use reference to pointer so we can do the erase safely
282 for(auto&& iter : mImpl->textureContainer)
287 mImpl->textureContainer.Erase(&iter); // Texture found; now destroy it
293 void RenderManager::UploadTexture(Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params)
295 texture->Upload(pixelData, params);
298 void RenderManager::GenerateMipmaps(Render::Texture* texture)
300 texture->GenerateMipmaps();
303 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
305 sampler->SetFilterMode(static_cast<Dali::FilterMode::Type>(minFilterMode),
306 static_cast<Dali::FilterMode::Type>(magFilterMode));
309 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
311 sampler->SetWrapMode(static_cast<Dali::WrapMode::Type>(rWrapMode),
312 static_cast<Dali::WrapMode::Type>(sWrapMode),
313 static_cast<Dali::WrapMode::Type>(tWrapMode));
316 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
318 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
319 mImpl->frameBufferContainer.PushBack(frameBufferPtr);
320 frameBufferPtr->Initialize(mImpl->context);
323 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
325 DALI_ASSERT_DEBUG(NULL != frameBuffer);
327 // Find the sampler, use reference so we can safely do the erase
328 for(auto&& iter : mImpl->frameBufferContainer)
330 if(iter == frameBuffer)
332 frameBuffer->Destroy(mImpl->context);
333 mImpl->frameBufferContainer.Erase(&iter); // frameBuffer found; now destroy it
340 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
342 scene->Initialize(*mImpl->CreateSceneContext());
343 mImpl->sceneContainer.push_back(scene);
346 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
348 mImpl->DestroySceneContext(scene->GetContext());
350 auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
351 if(iter != mImpl->sceneContainer.end())
353 mImpl->sceneContainer.erase(iter);
357 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
359 Context* newContext = mImpl->ReplaceSceneContext(scene->GetContext());
360 scene->Initialize(*newContext);
363 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
365 frameBuffer->AttachColorTexture(mImpl->context, texture, mipmapLevel, layer);
368 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
370 frameBuffer->AttachDepthTexture(mImpl->context, texture, mipmapLevel);
373 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
375 frameBuffer->AttachDepthStencilTexture(mImpl->context, texture, mipmapLevel);
378 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
380 mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
383 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
385 mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
388 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
390 vertexBuffer->SetFormat(format.Release());
393 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
395 vertexBuffer->SetData(data.Release(), size);
398 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Dali::Vector<uint16_t>& indices)
400 geometry->SetIndexBuffer(indices);
403 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
405 mImpl->geometryContainer.PushBack(geometry.Release());
408 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
410 mImpl->geometryContainer.EraseObject(geometry);
413 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
415 DALI_ASSERT_DEBUG(NULL != geometry);
418 for(auto&& iter : mImpl->geometryContainer)
422 iter->AddVertexBuffer(vertexBuffer);
428 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
430 DALI_ASSERT_DEBUG(NULL != geometry);
433 for(auto&& iter : mImpl->geometryContainer)
437 iter->RemoveVertexBuffer(vertexBuffer);
443 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
445 geometry->SetType(Render::Geometry::Type(geometryType));
448 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
450 mImpl->AddRenderTracker(renderTracker);
453 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
455 mImpl->RemoveRenderTracker(renderTracker);
458 ProgramCache* RenderManager::GetProgramCache()
460 return &(mImpl->programController);
463 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear, bool uploadOnly)
465 DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
467 // Core::Render documents that GL context must be current before calling Render
468 DALI_ASSERT_DEBUG(mImpl->context.IsGlContextCreated());
470 // Increment the frame count at the beginning of each frame
473 // Process messages queued during previous update
474 mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
477 for(uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i)
479 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count(mImpl->renderBufferIndex);
482 const bool haveInstructions = count > 0u;
484 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");
486 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
487 if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
489 DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
491 // Switch to the shared context
492 if(mImpl->currentContext != &mImpl->context)
494 mImpl->currentContext = &mImpl->context;
496 if(mImpl->currentContext->IsSurfacelessContextSupported())
498 mImpl->graphicsController.GetGlContextHelperAbstraction().MakeSurfacelessContextCurrent();
501 // Clear the current cached program when the context is switched
502 mImpl->programController.ClearCurrentProgram();
505 // Upload the geometries
506 for(uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i)
508 RenderInstructionContainer& instructions = mImpl->sceneContainer[i]->GetRenderInstructions();
509 for(uint32_t j = 0; j < instructions.Count(mImpl->renderBufferIndex); ++j)
511 RenderInstruction& instruction = instructions.At(mImpl->renderBufferIndex, j);
513 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
514 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
516 DALI_ASSERT_DEBUG(viewMatrix);
517 DALI_ASSERT_DEBUG(projectionMatrix);
519 if(viewMatrix && projectionMatrix)
521 const RenderListContainer::SizeType renderListCount = instruction.RenderListCount();
523 // Iterate through each render list.
524 for(RenderListContainer::SizeType index = 0; index < renderListCount; ++index)
526 const RenderList* renderList = instruction.GetRenderList(index);
528 if(renderList && !renderList->IsEmpty())
530 const std::size_t itemCount = renderList->Count();
531 for(uint32_t itemIndex = 0u; itemIndex < itemCount; ++itemIndex)
533 const RenderItem& item = renderList->GetItem(itemIndex);
534 if(DALI_LIKELY(item.mRenderer))
536 item.mRenderer->Upload();
547 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
549 if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
554 Internal::Scene& sceneInternal = GetImplementation(scene);
555 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
557 if(sceneObject->IsRenderingSkipped())
559 // We don't need to calculate dirty rects
563 class DamagedRectsCleaner
566 DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects)
567 : mDamagedRects(damagedRects),
572 void SetCleanOnReturn(bool cleanOnReturn)
574 mCleanOnReturn = cleanOnReturn;
577 ~DamagedRectsCleaner()
581 mDamagedRects.clear();
586 std::vector<Rect<int>>& mDamagedRects;
590 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
592 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
593 DamagedRectsCleaner damagedRectCleaner(damagedRects);
595 // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
596 // so you don't need to sort: std::stable_sort(itemsDirtyRects.begin(), itemsDirtyRects.end());
597 std::vector<DirtyRect>& itemsDirtyRects = sceneInternal.GetItemsDirtyRects();
598 for(DirtyRect& dirtyRect : itemsDirtyRects)
600 dirtyRect.visited = false;
603 uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
604 for(uint32_t i = 0; i < count; ++i)
606 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
608 if(instruction.mFrameBuffer)
610 return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
613 const Camera* camera = instruction.GetCamera();
614 if(camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
616 const Node* node = instruction.GetCamera()->GetNode();
621 Quaternion orientation;
622 node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
624 Vector3 orientationAxis;
625 Radian orientationAngle;
626 orientation.ToAxisAngle(orientationAxis, orientationAngle);
628 if(position.x > Math::MACHINE_EPSILON_10000 ||
629 position.y > Math::MACHINE_EPSILON_10000 ||
630 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
631 orientationAngle != ANGLE_180 ||
632 scale != Vector3(1.0f, 1.0f, 1.0f))
643 Rect<int32_t> viewportRect;
644 if(instruction.mIsViewportSet)
646 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
647 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
648 if(viewportRect.IsEmpty() || !viewportRect.IsValid())
650 return; // just skip funny use cases for now, empty viewport means it is set somewhere else
655 viewportRect = surfaceRect;
658 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
659 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
660 if(viewMatrix && projectionMatrix)
662 const RenderListContainer::SizeType count = instruction.RenderListCount();
663 for(RenderListContainer::SizeType index = 0u; index < count; ++index)
665 const RenderList* renderList = instruction.GetRenderList(index);
666 if(renderList && !renderList->IsEmpty())
668 const std::size_t count = renderList->Count();
669 for(uint32_t index = 0u; index < count; ++index)
671 RenderItem& item = renderList->GetItem(index);
672 // If the item does 3D transformation, do early exit and clean the damaged rect array
673 if(item.mUpdateSize == Vector3::ZERO)
679 DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
680 // If the item refers to updated node or renderer.
681 if(item.mIsUpdated ||
683 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
685 item.mIsUpdated = false;
686 item.mNode->SetUpdated(false);
688 rect = item.CalculateViewportSpaceAABB(item.mUpdateSize, viewportRect.width, viewportRect.height);
689 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
691 const int left = rect.x;
692 const int top = rect.y;
693 const int right = rect.x + rect.width;
694 const int bottom = rect.y + rect.height;
695 rect.x = (left / 16) * 16;
696 rect.y = (top / 16) * 16;
697 rect.width = ((right + 16) / 16) * 16 - rect.x;
698 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
700 // Found valid dirty rect.
701 // 1. Insert it in the sorted array of the dirty rects.
702 // 2. Mark the related dirty rects as visited so they will not be removed below.
703 // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
704 dirtyRect.rect = rect;
705 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
706 dirtyRectPos = itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
709 while(++dirtyRectPos != itemsDirtyRects.end())
711 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
716 dirtyRectPos->visited = true;
717 Rect<int>& dirtRect = dirtyRectPos->rect;
718 rect.Merge(dirtRect);
721 if(c > 3) // no more then 3 previous rects
723 itemsDirtyRects.erase(dirtyRectPos);
728 damagedRects.push_back(rect);
733 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
734 // 2. Mark the related dirty rects as visited so they will not be removed below.
735 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
736 while(dirtyRectPos != itemsDirtyRects.end())
738 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
743 dirtyRectPos->visited = true;
753 // Check removed nodes or removed renderers dirty rects
754 auto i = itemsDirtyRects.begin();
755 auto j = itemsDirtyRects.begin();
756 while(i != itemsDirtyRects.end())
764 Rect<int>& dirtRect = i->rect;
765 damagedRects.push_back(dirtRect);
770 itemsDirtyRects.resize(j - itemsDirtyRects.begin());
771 damagedRectCleaner.SetCleanOnReturn(false);
774 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
776 Rect<int> clippingRect;
777 RenderScene(status, scene, renderToFbo, clippingRect);
780 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
782 Internal::Scene& sceneInternal = GetImplementation(scene);
783 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
785 uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
787 for(uint32_t i = 0; i < count; ++i)
789 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
791 if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
796 // Mark that we will require a post-render step to be performed (includes swap-buffers).
797 status.SetNeedsPostRender(true);
799 Rect<int32_t> viewportRect;
802 if(instruction.mIsClearColorSet)
804 clearColor = instruction.mClearColor;
808 clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
811 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
812 int32_t surfaceOrientation = sceneObject->GetSurfaceOrientation();
814 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
815 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
817 if(instruction.mFrameBuffer)
820 if(mImpl->currentContext != &mImpl->context)
822 // Switch to shared context for off-screen buffer
823 mImpl->currentContext = &mImpl->context;
825 if(mImpl->currentContext->IsSurfacelessContextSupported())
827 mImpl->graphicsController.GetGlContextHelperAbstraction().MakeSurfacelessContextCurrent();
830 // Clear the current cached program when the context is switched
831 mImpl->programController.ClearCurrentProgram();
836 if(mImpl->currentContext->IsSurfacelessContextSupported())
838 if(mImpl->currentContext != sceneObject->GetContext())
840 // Switch the correct context if rendering to a surface
841 mImpl->currentContext = sceneObject->GetContext();
843 // Clear the current cached program when the context is switched
844 mImpl->programController.ClearCurrentProgram();
849 // Make sure that GL context must be created
850 mImpl->currentContext->GlContextCreated();
852 // reset the program matrices for all programs once per frame
853 // this ensures we will set view and projection matrix once per program per camera
854 mImpl->programController.ResetProgramMatrices();
856 if(instruction.mFrameBuffer)
858 instruction.mFrameBuffer->Bind(*mImpl->currentContext);
860 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
861 for(unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
863 mImpl->textureDependencyList.PushBack(instruction.mFrameBuffer->GetTexture(i0));
868 mImpl->currentContext->BindFramebuffer(GL_FRAMEBUFFER, 0u);
871 if(!instruction.mFrameBuffer)
873 mImpl->currentContext->Viewport(surfaceRect.x,
879 // Clear the entire color, depth and stencil buffers for the default framebuffer, if required.
880 // It is important to clear all 3 buffers when they are being used, for performance on deferred renderers
881 // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
882 // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
883 GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
885 mImpl->currentContext->ColorMask(true);
887 if(depthBufferAvailable == Integration::DepthBufferAvailable::TRUE)
889 mImpl->currentContext->DepthMask(true);
890 clearMask |= GL_DEPTH_BUFFER_BIT;
893 if(stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
895 mImpl->currentContext->ClearStencil(0);
896 mImpl->currentContext->StencilMask(0xFF); // 8 bit stencil mask, all 1's
897 clearMask |= GL_STENCIL_BUFFER_BIT;
900 if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
902 // Offscreen buffer rendering
903 if(instruction.mIsViewportSet)
905 // For glViewport the lower-left corner is (0,0)
906 const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
907 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
911 viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
913 surfaceOrientation = 0;
915 else // No Offscreen frame buffer rendering
917 // Check whether a viewport is specified, otherwise the full surface size is used
918 if(instruction.mIsViewportSet)
920 // For glViewport the lower-left corner is (0,0)
921 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
922 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
926 viewportRect = surfaceRect;
930 // Set surface orientation
931 mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
933 bool clearFullFrameRect = true;
934 if(instruction.mFrameBuffer != nullptr)
936 Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
937 clearFullFrameRect = (frameRect == viewportRect);
941 clearFullFrameRect = (surfaceRect == viewportRect);
944 if(!clippingRect.IsEmpty())
946 if(!clippingRect.Intersect(viewportRect))
948 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
949 clippingRect = Rect<int>();
951 clearFullFrameRect = false;
954 mImpl->currentContext->Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
956 if(instruction.mIsClearColorSet)
958 mImpl->currentContext->ClearColor(clearColor.r,
962 if(!clearFullFrameRect)
964 if(!clippingRect.IsEmpty())
966 mImpl->currentContext->SetScissorTest(true);
967 mImpl->currentContext->Scissor(clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
968 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
969 mImpl->currentContext->SetScissorTest(false);
973 mImpl->currentContext->SetScissorTest(true);
974 mImpl->currentContext->Scissor(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
975 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
976 mImpl->currentContext->SetScissorTest(false);
981 mImpl->currentContext->SetScissorTest(false);
982 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
986 // Clear the list of bound textures
987 mImpl->boundTextures.Clear();
989 mImpl->renderAlgorithms.ProcessRenderInstruction(
991 *mImpl->currentContext,
992 mImpl->renderBufferIndex,
993 depthBufferAvailable,
994 stencilBufferAvailable,
995 mImpl->boundTextures,
998 // Synchronise the FBO/Texture access when there are multiple contexts
999 if(mImpl->currentContext->IsSurfacelessContextSupported())
1001 // Check whether any bound texture is in the dependency list
1002 bool textureFound = false;
1004 if(mImpl->boundTextures.Count() > 0u && mImpl->textureDependencyList.Count() > 0u)
1006 for(auto texture : mImpl->textureDependencyList)
1008 textureFound = std::find_if(mImpl->boundTextures.Begin(), mImpl->boundTextures.End(), [texture](Graphics::Texture* graphicsTexture) {
1009 return texture == graphicsTexture;
1010 }) != mImpl->boundTextures.End();
1016 if(instruction.mFrameBuffer)
1018 // For off-screen buffer
1020 // Wait until all rendering calls for the currently context are executed
1021 mImpl->graphicsController.GetGlContextHelperAbstraction().WaitClient();
1023 // Clear the dependency list
1024 mImpl->textureDependencyList.Clear();
1028 // Worker thread lambda function
1029 auto& glContextHelperAbstraction = mImpl->graphicsController.GetGlContextHelperAbstraction();
1030 auto workerFunction = [&glContextHelperAbstraction](int workerThread) {
1031 // Switch to the shared context in the worker thread
1032 glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1034 // Wait until all rendering calls for the shared context are executed
1035 glContextHelperAbstraction.WaitClient();
1037 // Must clear the context in the worker thread
1038 // Otherwise the shared context cannot be switched to from the render thread
1039 glContextHelperAbstraction.MakeContextNull();
1042 auto future = mImpl->threadPool->SubmitTask(0u, workerFunction);
1045 mImpl->threadPool->Wait();
1047 // Clear the dependency list
1048 mImpl->textureDependencyList.Clear();
1054 if(instruction.mRenderTracker && instruction.mFrameBuffer)
1056 // This will create a sync object every frame this render tracker
1057 // is alive (though it should be now be created only for
1058 // render-once render tasks)
1059 instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController.GetGlSyncAbstraction());
1060 instruction.mRenderTracker = nullptr; // Only create once.
1065 mImpl->currentContext->Flush();
1069 GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
1070 mImpl->currentContext->InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1073 void RenderManager::PostRender(bool uploadOnly)
1077 if(mImpl->currentContext->IsSurfacelessContextSupported())
1079 mImpl->graphicsController.GetGlContextHelperAbstraction().MakeSurfacelessContextCurrent();
1082 GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
1083 mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1086 //Notify RenderGeometries that rendering has finished
1087 for(auto&& iter : mImpl->geometryContainer)
1089 iter->OnRenderFinished();
1092 mImpl->UpdateTrackers();
1094 uint32_t count = 0u;
1095 for(uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i)
1097 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count(mImpl->renderBufferIndex);
1100 const bool haveInstructions = count > 0u;
1102 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1103 mImpl->lastFrameWasRendered = haveInstructions;
1106 * The rendering has finished; swap to the next buffer.
1107 * Ideally the update has just finished using this buffer; otherwise the render thread
1108 * should block until the update has finished.
1110 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1112 DALI_PRINT_RENDER_END();
1115 } // namespace SceneGraph
1117 } // namespace Internal