2 * Copyright (c) 2020 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>
28 #include <dali/internal/event/common/scene-impl.h>
29 #include <dali/internal/render/common/render-algorithms.h>
30 #include <dali/internal/render/common/render-debug.h>
31 #include <dali/internal/render/common/render-tracker.h>
32 #include <dali/internal/render/queue/render-queue.h>
33 #include <dali/internal/render/shaders/program-controller.h>
44 #if defined(DEBUG_ENABLED)
47 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER" );
48 } // unnamed namespace
52 * Structure to contain internal data
54 struct RenderManager::Impl
56 Impl( Integration::GlAbstraction& glAbstraction,
57 Integration::GlSyncAbstraction& glSyncAbstraction,
58 Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
59 Integration::DepthBufferAvailable depthBufferAvailableParam,
60 Integration::StencilBufferAvailable stencilBufferAvailableParam,
61 Integration::PartialUpdateAvailable partialUpdateAvailableParam )
62 : context( glAbstraction, &sceneContextContainer ),
63 currentContext( &context ),
64 glAbstraction( glAbstraction ),
65 glSyncAbstraction( glSyncAbstraction ),
66 glContextHelperAbstraction( glContextHelperAbstraction ),
70 renderBufferIndex( SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX ),
75 frameBufferContainer(),
76 lastFrameWasRendered( false ),
77 programController( glAbstraction ),
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( glAbstraction );
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( glAbstraction );
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 Integration::GlAbstraction& glAbstraction; ///< GL abstraction
144 Integration::GlSyncAbstraction& glSyncAbstraction; ///< GL sync abstraction
145 Integration::GlContextHelperAbstraction& glContextHelperAbstraction; ///< GL context helper abstraction
146 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
148 std::vector< SceneGraph::Scene* > sceneContainer; ///< List of pointers to the scene graph objects of the scenes
150 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
152 uint32_t frameCount; ///< The current frame count
153 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
155 Rect<int32_t> defaultSurfaceRect; ///< Rectangle for the default surface we are rendering to
157 OwnerContainer< Render::Renderer* > rendererContainer; ///< List of owned renderers
158 OwnerContainer< Render::Sampler* > samplerContainer; ///< List of owned samplers
159 OwnerContainer< Render::Texture* > textureContainer; ///< List of owned textures
160 OwnerContainer< Render::FrameBuffer* > frameBufferContainer; ///< List of owned framebuffers
161 OwnerContainer< Render::VertexBuffer* > vertexBufferContainer; ///< List of owned vertex buffers
162 OwnerContainer< Render::Geometry* > geometryContainer; ///< List of owned Geometries
164 bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
166 OwnerContainer< Render::RenderTracker* > mRenderTrackers; ///< List of render trackers
168 ProgramController programController; ///< Owner of the GL programs
170 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
171 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
172 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
174 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
175 Vector<GLuint> boundTextures; ///< The textures bound for rendering
176 Vector<GLuint> textureDependencyList; ///< The dependency list of binded textures
179 RenderManager* RenderManager::New( Integration::GlAbstraction& glAbstraction,
180 Integration::GlSyncAbstraction& glSyncAbstraction,
181 Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
182 Integration::DepthBufferAvailable depthBufferAvailable,
183 Integration::StencilBufferAvailable stencilBufferAvailable,
184 Integration::PartialUpdateAvailable partialUpdateAvailable )
186 RenderManager* manager = new RenderManager;
187 manager->mImpl = new Impl( glAbstraction,
189 glContextHelperAbstraction,
190 depthBufferAvailable,
191 stencilBufferAvailable,
192 partialUpdateAvailable );
196 RenderManager::RenderManager()
201 RenderManager::~RenderManager()
206 RenderQueue& RenderManager::GetRenderQueue()
208 return mImpl->renderQueue;
211 void RenderManager::ContextCreated()
213 mImpl->context.GlContextCreated();
214 mImpl->programController.GlContextCreated();
216 // renderers, textures and gpu buffers cannot reinitialize themselves
217 // so they rely on someone reloading the data for them
220 void RenderManager::ContextDestroyed()
222 mImpl->context.GlContextDestroyed();
223 mImpl->programController.GlContextDestroyed();
226 for( auto&& texture : mImpl->textureContainer )
228 texture->GlContextDestroyed();
231 //Inform framebuffers
232 for( auto&& framebuffer : mImpl->frameBufferContainer )
234 framebuffer->GlContextDestroyed();
238 for( auto&& renderer : mImpl->rendererContainer )
240 renderer->GlContextDestroyed();
244 for( auto&& context : mImpl->sceneContextContainer )
246 context->GlContextDestroyed();
250 void RenderManager::SetShaderSaver( ShaderSaver& upstream )
252 mImpl->programController.SetShaderSaver( upstream );
255 void RenderManager::SetDefaultSurfaceRect(const Rect<int32_t>& rect)
257 mImpl->defaultSurfaceRect = rect;
260 void RenderManager::AddRenderer( OwnerPointer< Render::Renderer >& renderer )
262 // Initialize the renderer as we are now in render thread
263 renderer->Initialize( mImpl->context );
265 mImpl->rendererContainer.PushBack( renderer.Release() );
268 void RenderManager::RemoveRenderer( Render::Renderer* renderer )
270 mImpl->rendererContainer.EraseObject( renderer );
273 void RenderManager::AddSampler( OwnerPointer< Render::Sampler >& sampler )
275 mImpl->samplerContainer.PushBack( sampler.Release() );
278 void RenderManager::RemoveSampler( Render::Sampler* sampler )
280 mImpl->samplerContainer.EraseObject( sampler );
283 void RenderManager::AddTexture( OwnerPointer< Render::Texture >& texture )
285 texture->Initialize( mImpl->context );
286 mImpl->textureContainer.PushBack( texture.Release() );
289 void RenderManager::RemoveTexture( Render::Texture* texture )
291 DALI_ASSERT_DEBUG( NULL != texture );
293 // Find the texture, use reference to pointer so we can do the erase safely
294 for ( auto&& iter : mImpl->textureContainer )
296 if ( iter == texture )
298 texture->Destroy( mImpl->context );
299 mImpl->textureContainer.Erase( &iter ); // Texture found; now destroy it
305 void RenderManager::UploadTexture( Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params )
307 texture->Upload( mImpl->context, pixelData, params );
310 void RenderManager::GenerateMipmaps( Render::Texture* texture )
312 texture->GenerateMipmaps( mImpl->context );
315 void RenderManager::SetFilterMode( Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode )
317 sampler->mMinificationFilter = static_cast<Dali::FilterMode::Type>(minFilterMode);
318 sampler->mMagnificationFilter = static_cast<Dali::FilterMode::Type>(magFilterMode );
321 void RenderManager::SetWrapMode( Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode )
323 sampler->mRWrapMode = static_cast<Dali::WrapMode::Type>(rWrapMode);
324 sampler->mSWrapMode = static_cast<Dali::WrapMode::Type>(sWrapMode);
325 sampler->mTWrapMode = static_cast<Dali::WrapMode::Type>(tWrapMode);
328 void RenderManager::AddFrameBuffer( OwnerPointer< Render::FrameBuffer >& frameBuffer )
330 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
331 mImpl->frameBufferContainer.PushBack( frameBufferPtr );
332 frameBufferPtr->Initialize( mImpl->context );
335 void RenderManager::RemoveFrameBuffer( Render::FrameBuffer* frameBuffer )
337 DALI_ASSERT_DEBUG( NULL != frameBuffer );
339 // Find the sampler, use reference so we can safely do the erase
340 for ( auto&& iter : mImpl->frameBufferContainer )
342 if ( iter == frameBuffer )
344 frameBuffer->Destroy( mImpl->context );
345 mImpl->frameBufferContainer.Erase( &iter ); // frameBuffer found; now destroy it
351 void RenderManager::InitializeScene( SceneGraph::Scene* scene )
353 scene->Initialize( *mImpl->CreateSceneContext() );
354 mImpl->sceneContainer.push_back( scene );
357 void RenderManager::UninitializeScene( SceneGraph::Scene* scene )
359 mImpl->DestroySceneContext( scene->GetContext() );
361 auto iter = std::find( mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene );
362 if( iter != mImpl->sceneContainer.end() )
364 mImpl->sceneContainer.erase( iter );
368 void RenderManager::SurfaceReplaced( SceneGraph::Scene* scene )
370 Context* newContext = mImpl->ReplaceSceneContext( scene->GetContext() );
371 scene->Initialize( *newContext );
374 void RenderManager::AttachColorTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer )
376 frameBuffer->AttachColorTexture( mImpl->context, texture, mipmapLevel, layer );
379 void RenderManager::AttachDepthTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel )
381 frameBuffer->AttachDepthTexture( mImpl->context, texture, mipmapLevel );
384 void RenderManager::AttachDepthStencilTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel )
386 frameBuffer->AttachDepthStencilTexture( mImpl->context, texture, mipmapLevel );
389 void RenderManager::AddVertexBuffer( OwnerPointer< Render::VertexBuffer >& vertexBuffer )
391 mImpl->vertexBufferContainer.PushBack( vertexBuffer.Release() );
394 void RenderManager::RemoveVertexBuffer( Render::VertexBuffer* vertexBuffer )
396 mImpl->vertexBufferContainer.EraseObject( vertexBuffer );
399 void RenderManager::SetVertexBufferFormat( Render::VertexBuffer* vertexBuffer, OwnerPointer< Render::VertexBuffer::Format>& format )
401 vertexBuffer->SetFormat( format.Release() );
404 void RenderManager::SetVertexBufferData( Render::VertexBuffer* vertexBuffer, OwnerPointer< Vector<uint8_t> >& data, uint32_t size )
406 vertexBuffer->SetData( data.Release(), size );
409 void RenderManager::SetIndexBuffer( Render::Geometry* geometry, Dali::Vector<uint16_t>& indices )
411 geometry->SetIndexBuffer( indices );
414 void RenderManager::AddGeometry( OwnerPointer< Render::Geometry >& geometry )
416 mImpl->geometryContainer.PushBack( geometry.Release() );
419 void RenderManager::RemoveGeometry( Render::Geometry* geometry )
421 mImpl->geometryContainer.EraseObject( geometry );
424 void RenderManager::AttachVertexBuffer( Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer )
426 DALI_ASSERT_DEBUG( NULL != geometry );
429 for ( auto&& iter : mImpl->geometryContainer )
431 if ( iter == geometry )
433 iter->AddVertexBuffer( vertexBuffer );
439 void RenderManager::RemoveVertexBuffer( Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer )
441 DALI_ASSERT_DEBUG( NULL != geometry );
444 for ( auto&& iter : mImpl->geometryContainer )
446 if ( iter == geometry )
448 iter->RemoveVertexBuffer( vertexBuffer );
454 void RenderManager::SetGeometryType( Render::Geometry* geometry, uint32_t geometryType )
456 geometry->SetType( Render::Geometry::Type(geometryType) );
459 void RenderManager::AddRenderTracker( Render::RenderTracker* renderTracker )
461 mImpl->AddRenderTracker(renderTracker);
464 void RenderManager::RemoveRenderTracker( Render::RenderTracker* renderTracker )
466 mImpl->RemoveRenderTracker(renderTracker);
469 ProgramCache* RenderManager::GetProgramCache()
471 return &(mImpl->programController);
474 void RenderManager::PreRender( Integration::RenderStatus& status, bool forceClear, bool uploadOnly )
476 DALI_PRINT_RENDER_START( mImpl->renderBufferIndex );
478 // Core::Render documents that GL context must be current before calling Render
479 DALI_ASSERT_DEBUG( mImpl->context.IsGlContextCreated() );
481 // Increment the frame count at the beginning of each frame
484 // Process messages queued during previous update
485 mImpl->renderQueue.ProcessMessages( mImpl->renderBufferIndex );
488 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
490 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
493 const bool haveInstructions = count > 0u;
495 DALI_LOG_INFO( gLogFilter, Debug::General,
496 "Render: haveInstructions(%s) || mImpl->lastFrameWasRendered(%s) || forceClear(%s)\n",
497 haveInstructions ? "true" : "false",
498 mImpl->lastFrameWasRendered ? "true" : "false",
499 forceClear ? "true" : "false" );
501 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
502 if( haveInstructions || mImpl->lastFrameWasRendered || forceClear )
504 DALI_LOG_INFO( gLogFilter, Debug::General, "Render: Processing\n" );
506 // Switch to the shared context
507 if ( mImpl->currentContext != &mImpl->context )
509 mImpl->currentContext = &mImpl->context;
511 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
513 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
516 // Clear the current cached program when the context is switched
517 mImpl->programController.ClearCurrentProgram();
520 // Upload the geometries
521 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
523 RenderInstructionContainer& instructions = mImpl->sceneContainer[i]->GetRenderInstructions();
524 for ( uint32_t j = 0; j < instructions.Count( mImpl->renderBufferIndex ); ++j )
526 RenderInstruction& instruction = instructions.At( mImpl->renderBufferIndex, j );
528 const Matrix* viewMatrix = instruction.GetViewMatrix( mImpl->renderBufferIndex );
529 const Matrix* projectionMatrix = instruction.GetProjectionMatrix( mImpl->renderBufferIndex );
531 DALI_ASSERT_DEBUG( viewMatrix );
532 DALI_ASSERT_DEBUG( projectionMatrix );
534 if( viewMatrix && projectionMatrix )
536 const RenderListContainer::SizeType renderListCount = instruction.RenderListCount();
538 // Iterate through each render list.
539 for( RenderListContainer::SizeType index = 0; index < renderListCount; ++index )
541 const RenderList* renderList = instruction.GetRenderList( index );
543 if( renderList && !renderList->IsEmpty() )
545 const std::size_t itemCount = renderList->Count();
546 for( uint32_t itemIndex = 0u; itemIndex < itemCount; ++itemIndex )
548 const RenderItem& item = renderList->GetItem( itemIndex );
549 if( DALI_LIKELY( item.mRenderer ) )
551 item.mRenderer->Upload( *mImpl->currentContext );
562 void RenderManager::PreRender( Integration::Scene& scene, std::vector<Rect<int>>& damagedRects )
564 if (mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
569 class DamagedRectsCleaner
572 DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects)
573 : mDamagedRects(damagedRects),
578 void SetCleanOnReturn(bool cleanOnReturn)
580 mCleanOnReturn = cleanOnReturn;
583 ~DamagedRectsCleaner()
587 mDamagedRects.clear();
592 std::vector<Rect<int>>& mDamagedRects;
596 Rect<int32_t> surfaceRect = Rect<int32_t>(0, 0, static_cast<int32_t>( scene.GetSize().width ), static_cast<int32_t>( scene.GetSize().height ));
598 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
599 DamagedRectsCleaner damagedRectCleaner(damagedRects);
603 Internal::Scene& sceneInternal = GetImplementation(scene);
604 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
606 // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
607 // so you don't need to sort: std::stable_sort(itemsDirtyRects.begin(), itemsDirtyRects.end());
608 std::vector<DirtyRect>& itemsDirtyRects = sceneInternal.GetItemsDirtyRects();
609 for (DirtyRect& dirtyRect : itemsDirtyRects)
611 dirtyRect.visited = false;
614 uint32_t count = sceneObject->GetRenderInstructions().Count( mImpl->renderBufferIndex );
615 for (uint32_t i = 0; i < count; ++i)
617 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At( mImpl->renderBufferIndex, i );
619 if (instruction.mFrameBuffer)
621 return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
624 const Camera* camera = instruction.GetCamera();
625 if (camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
627 const Node* node = instruction.GetCamera()->GetNode();
632 Quaternion orientation;
633 node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
635 Vector3 orientationAxis;
636 Radian orientationAngle;
637 orientation.ToAxisAngle( orientationAxis, orientationAngle );
639 if (position.x > Math::MACHINE_EPSILON_10000 ||
640 position.y > Math::MACHINE_EPSILON_10000 ||
641 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
642 orientationAngle != ANGLE_180 ||
643 scale != Vector3(1.0f, 1.0f, 1.0f))
654 Rect<int32_t> viewportRect;
655 if (instruction.mIsViewportSet)
657 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
658 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
659 if (viewportRect.IsEmpty() || !viewportRect.IsValid())
661 return; // just skip funny use cases for now, empty viewport means it is set somewhere else
666 viewportRect = surfaceRect;
669 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
670 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
671 if (viewMatrix && projectionMatrix)
673 const RenderListContainer::SizeType count = instruction.RenderListCount();
674 for (RenderListContainer::SizeType index = 0u; index < count; ++index)
676 const RenderList* renderList = instruction.GetRenderList( index );
677 if (renderList && !renderList->IsEmpty())
679 const std::size_t count = renderList->Count();
680 for (uint32_t index = 0u; index < count; ++index)
682 RenderItem& item = renderList->GetItem( index );
683 // If the item does 3D transformation, do early exit and clean the damaged rect array
684 if (item.mUpdateSize == Vector3::ZERO)
690 DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
691 // If the item refers to updated node or renderer.
692 if (item.mIsUpdated ||
694 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
696 item.mIsUpdated = false;
697 item.mNode->SetUpdated(false);
699 rect = item.CalculateViewportSpaceAABB(item.mUpdateSize, viewportRect.width, viewportRect.height);
700 if (rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
702 const int left = rect.x;
703 const int top = rect.y;
704 const int right = rect.x + rect.width;
705 const int bottom = rect.y + rect.height;
706 rect.x = (left / 16) * 16;
707 rect.y = (top / 16) * 16;
708 rect.width = ((right + 16) / 16) * 16 - rect.x;
709 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
711 // Found valid dirty rect.
712 // 1. Insert it in the sorted array of the dirty rects.
713 // 2. Mark the related dirty rects as visited so they will not be removed below.
714 // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
715 dirtyRect.rect = rect;
716 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
717 dirtyRectPos = itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
720 while (++dirtyRectPos != itemsDirtyRects.end())
722 if (dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
727 dirtyRectPos->visited = true;
728 Rect<int>& dirtRect = dirtyRectPos->rect;
729 rect.Merge(dirtRect);
732 if (c > 3) // no more then 3 previous rects
734 itemsDirtyRects.erase(dirtyRectPos);
739 damagedRects.push_back(rect);
744 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
745 // 2. Mark the related dirty rects as visited so they will not be removed below.
746 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
747 while (dirtyRectPos != itemsDirtyRects.end())
749 if (dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
754 dirtyRectPos->visited = true;
764 // Check removed nodes or removed renderers dirty rects
765 auto i = itemsDirtyRects.begin();
766 auto j = itemsDirtyRects.begin();
767 while (i != itemsDirtyRects.end())
775 Rect<int>& dirtRect = i->rect;
776 damagedRects.push_back(dirtRect);
781 itemsDirtyRects.resize(j - itemsDirtyRects.begin());
782 damagedRectCleaner.SetCleanOnReturn(false);
785 void RenderManager::RenderScene( Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo )
787 Rect<int> clippingRect;
788 RenderScene( status, scene, renderToFbo, clippingRect);
791 void RenderManager::RenderScene( Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect )
793 Internal::Scene& sceneInternal = GetImplementation( scene );
794 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
796 uint32_t count = sceneObject->GetRenderInstructions().Count( mImpl->renderBufferIndex );
798 for( uint32_t i = 0; i < count; ++i )
800 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At( mImpl->renderBufferIndex, i );
802 if ( ( renderToFbo && !instruction.mFrameBuffer ) || ( !renderToFbo && instruction.mFrameBuffer ) )
807 // Mark that we will require a post-render step to be performed (includes swap-buffers).
808 status.SetNeedsPostRender( true );
810 Rect<int32_t> viewportRect;
813 if ( instruction.mIsClearColorSet )
815 clearColor = instruction.mClearColor;
819 clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
822 Rect<int32_t> surfaceRect = mImpl->defaultSurfaceRect;
823 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
824 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
826 if ( instruction.mFrameBuffer )
829 if ( mImpl->currentContext != &mImpl->context )
831 // Switch to shared context for off-screen buffer
832 mImpl->currentContext = &mImpl->context;
834 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
836 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
839 // Clear the current cached program when the context is switched
840 mImpl->programController.ClearCurrentProgram();
845 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
847 if ( mImpl->currentContext != sceneObject->GetContext() )
849 // Switch the correct context if rendering to a surface
850 mImpl->currentContext = sceneObject->GetContext();
852 // Clear the current cached program when the context is switched
853 mImpl->programController.ClearCurrentProgram();
857 surfaceRect = Rect<int32_t>( 0, 0, static_cast<int32_t>( scene.GetSize().width ), static_cast<int32_t>( scene.GetSize().height ) );
860 // Make sure that GL context must be created
861 mImpl->currentContext->GlContextCreated();
863 // reset the program matrices for all programs once per frame
864 // this ensures we will set view and projection matrix once per program per camera
865 mImpl->programController.ResetProgramMatrices();
867 if( instruction.mFrameBuffer )
869 instruction.mFrameBuffer->Bind( *mImpl->currentContext );
871 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
872 for (unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
874 mImpl->textureDependencyList.PushBack( instruction.mFrameBuffer->GetTextureId(i0) );
879 mImpl->currentContext->BindFramebuffer( GL_FRAMEBUFFER, 0u );
882 if ( !instruction.mFrameBuffer )
884 mImpl->currentContext->Viewport( surfaceRect.x,
887 surfaceRect.height );
890 // Clear the entire color, depth and stencil buffers for the default framebuffer, if required.
891 // It is important to clear all 3 buffers when they are being used, for performance on deferred renderers
892 // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
893 // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
894 GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
896 mImpl->currentContext->ColorMask( true );
898 if( depthBufferAvailable == Integration::DepthBufferAvailable::TRUE )
900 mImpl->currentContext->DepthMask( true );
901 clearMask |= GL_DEPTH_BUFFER_BIT;
904 if( stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
906 mImpl->currentContext->ClearStencil( 0 );
907 mImpl->currentContext->StencilMask( 0xFF ); // 8 bit stencil mask, all 1's
908 clearMask |= GL_STENCIL_BUFFER_BIT;
911 if( !instruction.mIgnoreRenderToFbo && ( instruction.mFrameBuffer != nullptr ) )
913 // Offscreen buffer rendering
914 if ( instruction.mIsViewportSet )
916 // For glViewport the lower-left corner is (0,0)
917 const int32_t y = ( instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height ) - instruction.mViewport.y;
918 viewportRect.Set( instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height );
922 viewportRect.Set( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
925 else // No Offscreen frame buffer rendering
927 // Check whether a viewport is specified, otherwise the full surface size is used
928 if ( instruction.mIsViewportSet )
930 // For glViewport the lower-left corner is (0,0)
931 const int32_t y = ( surfaceRect.height - instruction.mViewport.height ) - instruction.mViewport.y;
932 viewportRect.Set( instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height );
936 viewportRect = surfaceRect;
940 bool clearFullFrameRect = true;
941 if( instruction.mFrameBuffer != nullptr )
943 Viewport frameRect( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
944 clearFullFrameRect = ( frameRect == viewportRect );
948 clearFullFrameRect = ( surfaceRect == viewportRect );
951 if (!clippingRect.IsEmpty())
953 if (!clippingRect.Intersect(viewportRect))
955 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
956 clippingRect = Rect<int>();
958 clearFullFrameRect = false;
961 mImpl->currentContext->Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
963 if (instruction.mIsClearColorSet)
965 mImpl->currentContext->ClearColor(clearColor.r,
969 if (!clearFullFrameRect)
971 if (!clippingRect.IsEmpty())
973 mImpl->currentContext->SetScissorTest(true);
974 mImpl->currentContext->Scissor(clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
975 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
976 mImpl->currentContext->SetScissorTest(false);
980 mImpl->currentContext->SetScissorTest(true);
981 mImpl->currentContext->Scissor(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
982 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
983 mImpl->currentContext->SetScissorTest(false);
988 mImpl->currentContext->SetScissorTest(false);
989 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
993 // Clear the list of bound textures
994 mImpl->boundTextures.Clear();
996 mImpl->renderAlgorithms.ProcessRenderInstruction(
998 *mImpl->currentContext,
999 mImpl->renderBufferIndex,
1000 depthBufferAvailable,
1001 stencilBufferAvailable,
1002 mImpl->boundTextures,
1005 // Synchronise the FBO/Texture access when there are multiple contexts
1006 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
1008 // Check whether any binded texture is in the dependency list
1009 bool textureFound = false;
1011 if ( mImpl->boundTextures.Count() > 0u && mImpl->textureDependencyList.Count() > 0u )
1013 for ( auto textureId : mImpl->textureDependencyList )
1016 textureFound = std::find_if( mImpl->boundTextures.Begin(), mImpl->boundTextures.End(),
1017 [textureId]( GLuint id )
1019 return textureId == id;
1020 } ) != mImpl->boundTextures.End();
1026 if ( instruction.mFrameBuffer )
1028 // For off-screen buffer
1030 // Wait until all rendering calls for the currently context are executed
1031 mImpl->glContextHelperAbstraction.WaitClient();
1033 // Clear the dependency list
1034 mImpl->textureDependencyList.Clear();
1038 // Worker thread lambda function
1039 auto& glContextHelperAbstraction = mImpl->glContextHelperAbstraction;
1040 auto workerFunction = [&glContextHelperAbstraction]( int workerThread )
1042 // Switch to the shared context in the worker thread
1043 glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1045 // Wait until all rendering calls for the shared context are executed
1046 glContextHelperAbstraction.WaitClient();
1048 // Must clear the context in the worker thread
1049 // Otherwise the shared context cannot be switched to from the render thread
1050 glContextHelperAbstraction.MakeContextNull();
1053 auto future = mImpl->threadPool->SubmitTask( 0u, workerFunction );
1056 mImpl->threadPool->Wait();
1058 // Clear the dependency list
1059 mImpl->textureDependencyList.Clear();
1065 if( instruction.mRenderTracker && instruction.mFrameBuffer )
1067 // This will create a sync object every frame this render tracker
1068 // is alive (though it should be now be created only for
1069 // render-once render tasks)
1070 instruction.mRenderTracker->CreateSyncObject( mImpl->glSyncAbstraction );
1071 instruction.mRenderTracker = nullptr; // Only create once.
1076 mImpl->currentContext->Flush();
1080 GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
1081 mImpl->currentContext->InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1084 void RenderManager::PostRender( bool uploadOnly )
1088 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
1090 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1093 GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
1094 mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1097 //Notify RenderGeometries that rendering has finished
1098 for ( auto&& iter : mImpl->geometryContainer )
1100 iter->OnRenderFinished();
1103 mImpl->UpdateTrackers();
1106 uint32_t count = 0u;
1107 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
1109 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
1112 const bool haveInstructions = count > 0u;
1114 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1115 mImpl->lastFrameWasRendered = haveInstructions;
1118 * The rendering has finished; swap to the next buffer.
1119 * Ideally the update has just finished using this buffer; otherwise the render thread
1120 * should block until the update has finished.
1122 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1124 DALI_PRINT_RENDER_END();
1127 } // namespace SceneGraph
1129 } // namespace Internal