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 ),
81 defaultSurfaceOrientation(0)
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 );
90 threadPool.reset( nullptr ); // reset now to maintain correct destruction order
93 void AddRenderTracker( Render::RenderTracker* renderTracker )
95 DALI_ASSERT_DEBUG( renderTracker != NULL );
96 mRenderTrackers.PushBack( renderTracker );
99 void RemoveRenderTracker( Render::RenderTracker* renderTracker )
101 mRenderTrackers.EraseObject( renderTracker );
104 Context* CreateSceneContext()
106 Context* context = new Context( glAbstraction );
107 sceneContextContainer.PushBack( context );
111 void DestroySceneContext( Context* sceneContext )
113 auto iter = std::find( sceneContextContainer.Begin(), sceneContextContainer.End(), sceneContext );
114 if( iter != sceneContextContainer.End() )
116 ( *iter )->GlContextDestroyed();
117 sceneContextContainer.Erase( iter );
121 Context* ReplaceSceneContext( Context* oldSceneContext )
123 Context* newContext = new Context( glAbstraction );
125 oldSceneContext->GlContextDestroyed();
127 std::replace( sceneContextContainer.begin(), sceneContextContainer.end(), oldSceneContext, newContext );
131 void UpdateTrackers()
133 for( auto&& iter : mRenderTrackers )
135 iter->PollSyncObject();
139 // the order is important for destruction,
140 // programs are owned by context at the moment.
141 Context context; ///< Holds the GL state of the share resource context
142 Context* currentContext; ///< Holds the GL state of the current context for rendering
143 OwnerContainer< Context* > sceneContextContainer; ///< List of owned contexts holding the GL state per scene
144 Integration::GlAbstraction& glAbstraction; ///< GL abstraction
145 Integration::GlSyncAbstraction& glSyncAbstraction; ///< GL sync abstraction
146 Integration::GlContextHelperAbstraction& glContextHelperAbstraction; ///< GL context helper abstraction
147 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
149 std::vector< SceneGraph::Scene* > sceneContainer; ///< List of pointers to the scene graph objects of the scenes
151 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
153 uint32_t frameCount; ///< The current frame count
154 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
156 Rect<int32_t> defaultSurfaceRect; ///< Rectangle for the default surface we are rendering to
158 OwnerContainer< Render::Renderer* > rendererContainer; ///< List of owned renderers
159 OwnerContainer< Render::Sampler* > samplerContainer; ///< List of owned samplers
160 OwnerContainer< Render::Texture* > textureContainer; ///< List of owned textures
161 OwnerContainer< Render::FrameBuffer* > frameBufferContainer; ///< List of owned framebuffers
162 OwnerContainer< Render::VertexBuffer* > vertexBufferContainer; ///< List of owned vertex buffers
163 OwnerContainer< Render::Geometry* > geometryContainer; ///< List of owned Geometries
165 bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
167 OwnerContainer< Render::RenderTracker* > mRenderTrackers; ///< List of render trackers
169 ProgramController programController; ///< Owner of the GL programs
171 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
172 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
173 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
175 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
176 Vector<GLuint> boundTextures; ///< The textures bound for rendering
177 Vector<GLuint> textureDependencyList; ///< The dependency list of binded textures
179 int defaultSurfaceOrientation; ///< defaultSurfaceOrientation for the default surface we are rendering to
183 RenderManager* RenderManager::New( Integration::GlAbstraction& glAbstraction,
184 Integration::GlSyncAbstraction& glSyncAbstraction,
185 Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
186 Integration::DepthBufferAvailable depthBufferAvailable,
187 Integration::StencilBufferAvailable stencilBufferAvailable,
188 Integration::PartialUpdateAvailable partialUpdateAvailable )
190 RenderManager* manager = new RenderManager;
191 manager->mImpl = new Impl( glAbstraction,
193 glContextHelperAbstraction,
194 depthBufferAvailable,
195 stencilBufferAvailable,
196 partialUpdateAvailable );
200 RenderManager::RenderManager()
205 RenderManager::~RenderManager()
210 RenderQueue& RenderManager::GetRenderQueue()
212 return mImpl->renderQueue;
215 void RenderManager::ContextCreated()
217 mImpl->context.GlContextCreated();
218 mImpl->programController.GlContextCreated();
220 // renderers, textures and gpu buffers cannot reinitialize themselves
221 // so they rely on someone reloading the data for them
224 void RenderManager::ContextDestroyed()
226 mImpl->context.GlContextDestroyed();
227 mImpl->programController.GlContextDestroyed();
230 for( auto&& texture : mImpl->textureContainer )
232 texture->GlContextDestroyed();
235 //Inform framebuffers
236 for( auto&& framebuffer : mImpl->frameBufferContainer )
238 framebuffer->GlContextDestroyed();
242 for( auto&& renderer : mImpl->rendererContainer )
244 renderer->GlContextDestroyed();
248 for( auto&& context : mImpl->sceneContextContainer )
250 context->GlContextDestroyed();
254 void RenderManager::SetShaderSaver( ShaderSaver& upstream )
256 mImpl->programController.SetShaderSaver( upstream );
259 void RenderManager::SetDefaultSurfaceRect(const Rect<int32_t>& rect)
261 mImpl->defaultSurfaceRect = rect;
264 void RenderManager::SetDefaultSurfaceOrientation(int orientation)
266 mImpl->defaultSurfaceOrientation = orientation;
269 void RenderManager::AddRenderer( OwnerPointer< Render::Renderer >& renderer )
271 // Initialize the renderer as we are now in render thread
272 renderer->Initialize( mImpl->context );
274 mImpl->rendererContainer.PushBack( renderer.Release() );
277 void RenderManager::RemoveRenderer( Render::Renderer* renderer )
279 mImpl->rendererContainer.EraseObject( renderer );
282 void RenderManager::AddSampler( OwnerPointer< Render::Sampler >& sampler )
284 mImpl->samplerContainer.PushBack( sampler.Release() );
287 void RenderManager::RemoveSampler( Render::Sampler* sampler )
289 mImpl->samplerContainer.EraseObject( sampler );
292 void RenderManager::AddTexture( OwnerPointer< Render::Texture >& texture )
294 texture->Initialize( mImpl->context );
295 mImpl->textureContainer.PushBack( texture.Release() );
298 void RenderManager::RemoveTexture( Render::Texture* texture )
300 DALI_ASSERT_DEBUG( NULL != texture );
302 // Find the texture, use reference to pointer so we can do the erase safely
303 for ( auto&& iter : mImpl->textureContainer )
305 if ( iter == texture )
307 texture->Destroy( mImpl->context );
308 mImpl->textureContainer.Erase( &iter ); // Texture found; now destroy it
314 void RenderManager::UploadTexture( Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params )
316 texture->Upload( mImpl->context, pixelData, params );
319 void RenderManager::GenerateMipmaps( Render::Texture* texture )
321 texture->GenerateMipmaps( mImpl->context );
324 void RenderManager::SetFilterMode( Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode )
326 sampler->mMinificationFilter = static_cast<Dali::FilterMode::Type>(minFilterMode);
327 sampler->mMagnificationFilter = static_cast<Dali::FilterMode::Type>(magFilterMode );
330 void RenderManager::SetWrapMode( Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode )
332 sampler->mRWrapMode = static_cast<Dali::WrapMode::Type>(rWrapMode);
333 sampler->mSWrapMode = static_cast<Dali::WrapMode::Type>(sWrapMode);
334 sampler->mTWrapMode = static_cast<Dali::WrapMode::Type>(tWrapMode);
337 void RenderManager::AddFrameBuffer( OwnerPointer< Render::FrameBuffer >& frameBuffer )
339 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
340 mImpl->frameBufferContainer.PushBack( frameBufferPtr );
341 frameBufferPtr->Initialize( mImpl->context );
344 void RenderManager::RemoveFrameBuffer( Render::FrameBuffer* frameBuffer )
346 DALI_ASSERT_DEBUG( NULL != frameBuffer );
348 // Find the sampler, use reference so we can safely do the erase
349 for ( auto&& iter : mImpl->frameBufferContainer )
351 if ( iter == frameBuffer )
353 frameBuffer->Destroy( mImpl->context );
354 mImpl->frameBufferContainer.Erase( &iter ); // frameBuffer found; now destroy it
360 void RenderManager::InitializeScene( SceneGraph::Scene* scene )
362 scene->Initialize( *mImpl->CreateSceneContext() );
363 mImpl->sceneContainer.push_back( scene );
366 void RenderManager::UninitializeScene( SceneGraph::Scene* scene )
368 mImpl->DestroySceneContext( scene->GetContext() );
370 auto iter = std::find( mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene );
371 if( iter != mImpl->sceneContainer.end() )
373 mImpl->sceneContainer.erase( iter );
377 void RenderManager::SurfaceReplaced( SceneGraph::Scene* scene )
379 Context* newContext = mImpl->ReplaceSceneContext( scene->GetContext() );
380 scene->Initialize( *newContext );
383 void RenderManager::AttachColorTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer )
385 frameBuffer->AttachColorTexture( mImpl->context, texture, mipmapLevel, layer );
388 void RenderManager::AttachDepthTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel )
390 frameBuffer->AttachDepthTexture( mImpl->context, texture, mipmapLevel );
393 void RenderManager::AttachDepthStencilTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel )
395 frameBuffer->AttachDepthStencilTexture( mImpl->context, texture, mipmapLevel );
398 void RenderManager::AddVertexBuffer( OwnerPointer< Render::VertexBuffer >& vertexBuffer )
400 mImpl->vertexBufferContainer.PushBack( vertexBuffer.Release() );
403 void RenderManager::RemoveVertexBuffer( Render::VertexBuffer* vertexBuffer )
405 mImpl->vertexBufferContainer.EraseObject( vertexBuffer );
408 void RenderManager::SetVertexBufferFormat( Render::VertexBuffer* vertexBuffer, OwnerPointer< Render::VertexBuffer::Format>& format )
410 vertexBuffer->SetFormat( format.Release() );
413 void RenderManager::SetVertexBufferData( Render::VertexBuffer* vertexBuffer, OwnerPointer< Vector<uint8_t> >& data, uint32_t size )
415 vertexBuffer->SetData( data.Release(), size );
418 void RenderManager::SetIndexBuffer( Render::Geometry* geometry, Dali::Vector<uint16_t>& indices )
420 geometry->SetIndexBuffer( indices );
423 void RenderManager::AddGeometry( OwnerPointer< Render::Geometry >& geometry )
425 mImpl->geometryContainer.PushBack( geometry.Release() );
428 void RenderManager::RemoveGeometry( Render::Geometry* geometry )
430 mImpl->geometryContainer.EraseObject( geometry );
433 void RenderManager::AttachVertexBuffer( Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer )
435 DALI_ASSERT_DEBUG( NULL != geometry );
438 for ( auto&& iter : mImpl->geometryContainer )
440 if ( iter == geometry )
442 iter->AddVertexBuffer( vertexBuffer );
448 void RenderManager::RemoveVertexBuffer( Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer )
450 DALI_ASSERT_DEBUG( NULL != geometry );
453 for ( auto&& iter : mImpl->geometryContainer )
455 if ( iter == geometry )
457 iter->RemoveVertexBuffer( vertexBuffer );
463 void RenderManager::SetGeometryType( Render::Geometry* geometry, uint32_t geometryType )
465 geometry->SetType( Render::Geometry::Type(geometryType) );
468 void RenderManager::AddRenderTracker( Render::RenderTracker* renderTracker )
470 mImpl->AddRenderTracker(renderTracker);
473 void RenderManager::RemoveRenderTracker( Render::RenderTracker* renderTracker )
475 mImpl->RemoveRenderTracker(renderTracker);
478 ProgramCache* RenderManager::GetProgramCache()
480 return &(mImpl->programController);
483 void RenderManager::PreRender( Integration::RenderStatus& status, bool forceClear, bool uploadOnly )
485 DALI_PRINT_RENDER_START( mImpl->renderBufferIndex );
487 // Core::Render documents that GL context must be current before calling Render
488 DALI_ASSERT_DEBUG( mImpl->context.IsGlContextCreated() );
490 // Increment the frame count at the beginning of each frame
493 // Process messages queued during previous update
494 mImpl->renderQueue.ProcessMessages( mImpl->renderBufferIndex );
497 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
499 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
502 const bool haveInstructions = count > 0u;
504 DALI_LOG_INFO( gLogFilter, Debug::General,
505 "Render: haveInstructions(%s) || mImpl->lastFrameWasRendered(%s) || forceClear(%s)\n",
506 haveInstructions ? "true" : "false",
507 mImpl->lastFrameWasRendered ? "true" : "false",
508 forceClear ? "true" : "false" );
510 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
511 if( haveInstructions || mImpl->lastFrameWasRendered || forceClear )
513 DALI_LOG_INFO( gLogFilter, Debug::General, "Render: Processing\n" );
515 // Switch to the shared context
516 if ( mImpl->currentContext != &mImpl->context )
518 mImpl->currentContext = &mImpl->context;
520 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
522 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
525 // Clear the current cached program when the context is switched
526 mImpl->programController.ClearCurrentProgram();
529 // Upload the geometries
530 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
532 RenderInstructionContainer& instructions = mImpl->sceneContainer[i]->GetRenderInstructions();
533 for ( uint32_t j = 0; j < instructions.Count( mImpl->renderBufferIndex ); ++j )
535 RenderInstruction& instruction = instructions.At( mImpl->renderBufferIndex, j );
537 const Matrix* viewMatrix = instruction.GetViewMatrix( mImpl->renderBufferIndex );
538 const Matrix* projectionMatrix = instruction.GetProjectionMatrix( mImpl->renderBufferIndex );
540 DALI_ASSERT_DEBUG( viewMatrix );
541 DALI_ASSERT_DEBUG( projectionMatrix );
543 if( viewMatrix && projectionMatrix )
545 const RenderListContainer::SizeType renderListCount = instruction.RenderListCount();
547 // Iterate through each render list.
548 for( RenderListContainer::SizeType index = 0; index < renderListCount; ++index )
550 const RenderList* renderList = instruction.GetRenderList( index );
552 if( renderList && !renderList->IsEmpty() )
554 const std::size_t itemCount = renderList->Count();
555 for( uint32_t itemIndex = 0u; itemIndex < itemCount; ++itemIndex )
557 const RenderItem& item = renderList->GetItem( itemIndex );
558 if( DALI_LIKELY( item.mRenderer ) )
560 item.mRenderer->Upload( *mImpl->currentContext );
571 void RenderManager::PreRender( Integration::Scene& scene, std::vector<Rect<int>>& damagedRects )
573 if (mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
578 // @TODO We need to do partial rendering rotation.
579 if( mImpl->defaultSurfaceOrientation != 0 )
584 class DamagedRectsCleaner
587 DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects)
588 : mDamagedRects(damagedRects),
593 void SetCleanOnReturn(bool cleanOnReturn)
595 mCleanOnReturn = cleanOnReturn;
598 ~DamagedRectsCleaner()
602 mDamagedRects.clear();
607 std::vector<Rect<int>>& mDamagedRects;
611 Rect<int32_t> surfaceRect = Rect<int32_t>(0, 0, static_cast<int32_t>( scene.GetSize().width ), static_cast<int32_t>( scene.GetSize().height ));
613 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
614 DamagedRectsCleaner damagedRectCleaner(damagedRects);
618 Internal::Scene& sceneInternal = GetImplementation(scene);
619 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
621 // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
622 // so you don't need to sort: std::stable_sort(itemsDirtyRects.begin(), itemsDirtyRects.end());
623 std::vector<DirtyRect>& itemsDirtyRects = sceneInternal.GetItemsDirtyRects();
624 for (DirtyRect& dirtyRect : itemsDirtyRects)
626 dirtyRect.visited = false;
629 uint32_t count = sceneObject->GetRenderInstructions().Count( mImpl->renderBufferIndex );
630 for (uint32_t i = 0; i < count; ++i)
632 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At( mImpl->renderBufferIndex, i );
634 if (instruction.mFrameBuffer)
636 return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
639 const Camera* camera = instruction.GetCamera();
640 if (camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
642 const Node* node = instruction.GetCamera()->GetNode();
647 Quaternion orientation;
648 node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
650 Vector3 orientationAxis;
651 Radian orientationAngle;
652 orientation.ToAxisAngle( orientationAxis, orientationAngle );
654 if (position.x > Math::MACHINE_EPSILON_10000 ||
655 position.y > Math::MACHINE_EPSILON_10000 ||
656 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
657 orientationAngle != ANGLE_180 ||
658 scale != Vector3(1.0f, 1.0f, 1.0f))
669 Rect<int32_t> viewportRect;
670 if (instruction.mIsViewportSet)
672 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
673 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
674 if (viewportRect.IsEmpty() || !viewportRect.IsValid())
676 return; // just skip funny use cases for now, empty viewport means it is set somewhere else
681 viewportRect = surfaceRect;
684 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
685 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
686 if (viewMatrix && projectionMatrix)
688 const RenderListContainer::SizeType count = instruction.RenderListCount();
689 for (RenderListContainer::SizeType index = 0u; index < count; ++index)
691 const RenderList* renderList = instruction.GetRenderList( index );
692 if (renderList && !renderList->IsEmpty())
694 const std::size_t count = renderList->Count();
695 for (uint32_t index = 0u; index < count; ++index)
697 RenderItem& item = renderList->GetItem( index );
698 // If the item does 3D transformation, do early exit and clean the damaged rect array
699 if (item.mUpdateSize == Vector3::ZERO)
705 DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
706 // If the item refers to updated node or renderer.
707 if (item.mIsUpdated ||
709 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
711 item.mIsUpdated = false;
712 item.mNode->SetUpdated(false);
714 rect = item.CalculateViewportSpaceAABB(item.mUpdateSize, viewportRect.width, viewportRect.height);
715 if (rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
717 const int left = rect.x;
718 const int top = rect.y;
719 const int right = rect.x + rect.width;
720 const int bottom = rect.y + rect.height;
721 rect.x = (left / 16) * 16;
722 rect.y = (top / 16) * 16;
723 rect.width = ((right + 16) / 16) * 16 - rect.x;
724 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
726 // Found valid dirty rect.
727 // 1. Insert it in the sorted array of the dirty rects.
728 // 2. Mark the related dirty rects as visited so they will not be removed below.
729 // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
730 dirtyRect.rect = rect;
731 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
732 dirtyRectPos = itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
735 while (++dirtyRectPos != itemsDirtyRects.end())
737 if (dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
742 dirtyRectPos->visited = true;
743 Rect<int>& dirtRect = dirtyRectPos->rect;
744 rect.Merge(dirtRect);
747 if (c > 3) // no more then 3 previous rects
749 itemsDirtyRects.erase(dirtyRectPos);
754 damagedRects.push_back(rect);
759 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
760 // 2. Mark the related dirty rects as visited so they will not be removed below.
761 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
762 while (dirtyRectPos != itemsDirtyRects.end())
764 if (dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
769 dirtyRectPos->visited = true;
779 // Check removed nodes or removed renderers dirty rects
780 auto i = itemsDirtyRects.begin();
781 auto j = itemsDirtyRects.begin();
782 while (i != itemsDirtyRects.end())
790 Rect<int>& dirtRect = i->rect;
791 damagedRects.push_back(dirtRect);
796 itemsDirtyRects.resize(j - itemsDirtyRects.begin());
797 damagedRectCleaner.SetCleanOnReturn(false);
800 void RenderManager::RenderScene( Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo )
802 Rect<int> clippingRect;
803 RenderScene( status, scene, renderToFbo, clippingRect);
806 void RenderManager::RenderScene( Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect )
808 Internal::Scene& sceneInternal = GetImplementation( scene );
809 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
811 uint32_t count = sceneObject->GetRenderInstructions().Count( mImpl->renderBufferIndex );
813 for( uint32_t i = 0; i < count; ++i )
815 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At( mImpl->renderBufferIndex, i );
817 if ( ( renderToFbo && !instruction.mFrameBuffer ) || ( !renderToFbo && instruction.mFrameBuffer ) )
822 // Mark that we will require a post-render step to be performed (includes swap-buffers).
823 status.SetNeedsPostRender( true );
825 Rect<int32_t> viewportRect;
828 if ( instruction.mIsClearColorSet )
830 clearColor = instruction.mClearColor;
834 clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
837 Rect<int32_t> surfaceRect = mImpl->defaultSurfaceRect;
838 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
839 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
840 int surfaceOrientation = sceneInternal.GetSurfaceOrientation();
842 if ( instruction.mFrameBuffer )
845 if ( mImpl->currentContext != &mImpl->context )
847 // Switch to shared context for off-screen buffer
848 mImpl->currentContext = &mImpl->context;
850 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
852 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
855 // Clear the current cached program when the context is switched
856 mImpl->programController.ClearCurrentProgram();
861 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
863 if ( mImpl->currentContext != sceneObject->GetContext() )
865 // Switch the correct context if rendering to a surface
866 mImpl->currentContext = sceneObject->GetContext();
868 // Clear the current cached program when the context is switched
869 mImpl->programController.ClearCurrentProgram();
873 surfaceRect = Rect<int32_t>( 0, 0, static_cast<int32_t>( scene.GetSize().width ), static_cast<int32_t>( scene.GetSize().height ) );
876 // Make sure that GL context must be created
877 mImpl->currentContext->GlContextCreated();
879 // reset the program matrices for all programs once per frame
880 // this ensures we will set view and projection matrix once per program per camera
881 mImpl->programController.ResetProgramMatrices();
883 if( instruction.mFrameBuffer )
885 instruction.mFrameBuffer->Bind( *mImpl->currentContext );
887 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
888 for (unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
890 mImpl->textureDependencyList.PushBack( instruction.mFrameBuffer->GetTextureId(i0) );
895 mImpl->currentContext->BindFramebuffer( GL_FRAMEBUFFER, 0u );
898 if ( !instruction.mFrameBuffer )
900 mImpl->currentContext->Viewport( surfaceRect.x,
903 surfaceRect.height );
906 // Clear the entire color, depth and stencil buffers for the default framebuffer, if required.
907 // It is important to clear all 3 buffers when they are being used, for performance on deferred renderers
908 // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
909 // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
910 GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
912 mImpl->currentContext->ColorMask( true );
914 if( depthBufferAvailable == Integration::DepthBufferAvailable::TRUE )
916 mImpl->currentContext->DepthMask( true );
917 clearMask |= GL_DEPTH_BUFFER_BIT;
920 if( stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
922 mImpl->currentContext->ClearStencil( 0 );
923 mImpl->currentContext->StencilMask( 0xFF ); // 8 bit stencil mask, all 1's
924 clearMask |= GL_STENCIL_BUFFER_BIT;
927 if( !instruction.mIgnoreRenderToFbo && ( instruction.mFrameBuffer != nullptr ) )
929 // Offscreen buffer rendering
930 if ( instruction.mIsViewportSet )
932 // For glViewport the lower-left corner is (0,0)
933 const int32_t y = ( instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height ) - instruction.mViewport.y;
934 viewportRect.Set( instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height );
938 viewportRect.Set( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
940 surfaceOrientation = 0;
942 else // No Offscreen frame buffer rendering
944 // Check whether a viewport is specified, otherwise the full surface size is used
945 if ( instruction.mIsViewportSet )
947 // For glViewport the lower-left corner is (0,0)
948 const int32_t y = ( surfaceRect.height - instruction.mViewport.height ) - instruction.mViewport.y;
949 viewportRect.Set( instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height );
953 viewportRect = surfaceRect;
957 // Set surface orientation
958 mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
960 bool clearFullFrameRect = true;
961 if( instruction.mFrameBuffer != nullptr )
963 Viewport frameRect( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
964 clearFullFrameRect = ( frameRect == viewportRect );
968 clearFullFrameRect = ( surfaceRect == viewportRect );
971 if (!clippingRect.IsEmpty())
973 if (!clippingRect.Intersect(viewportRect))
975 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
976 clippingRect = Rect<int>();
978 clearFullFrameRect = false;
981 mImpl->currentContext->Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
983 if (instruction.mIsClearColorSet)
985 mImpl->currentContext->ClearColor(clearColor.r,
989 if (!clearFullFrameRect)
991 if (!clippingRect.IsEmpty())
993 mImpl->currentContext->SetScissorTest(true);
994 mImpl->currentContext->Scissor(clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
995 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
996 mImpl->currentContext->SetScissorTest(false);
1000 mImpl->currentContext->SetScissorTest(true);
1001 mImpl->currentContext->Scissor(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
1002 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
1003 mImpl->currentContext->SetScissorTest(false);
1008 mImpl->currentContext->SetScissorTest(false);
1009 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
1013 // Clear the list of bound textures
1014 mImpl->boundTextures.Clear();
1016 mImpl->renderAlgorithms.ProcessRenderInstruction(
1018 *mImpl->currentContext,
1019 mImpl->renderBufferIndex,
1020 depthBufferAvailable,
1021 stencilBufferAvailable,
1022 mImpl->boundTextures,
1025 // Synchronise the FBO/Texture access when there are multiple contexts
1026 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
1028 // Check whether any binded texture is in the dependency list
1029 bool textureFound = false;
1031 if ( mImpl->boundTextures.Count() > 0u && mImpl->textureDependencyList.Count() > 0u )
1033 for ( auto textureId : mImpl->textureDependencyList )
1036 textureFound = std::find_if( mImpl->boundTextures.Begin(), mImpl->boundTextures.End(),
1037 [textureId]( GLuint id )
1039 return textureId == id;
1040 } ) != mImpl->boundTextures.End();
1046 if ( instruction.mFrameBuffer )
1048 // For off-screen buffer
1050 // Wait until all rendering calls for the currently context are executed
1051 mImpl->glContextHelperAbstraction.WaitClient();
1053 // Clear the dependency list
1054 mImpl->textureDependencyList.Clear();
1058 // Worker thread lambda function
1059 auto& glContextHelperAbstraction = mImpl->glContextHelperAbstraction;
1060 auto workerFunction = [&glContextHelperAbstraction]( int workerThread )
1062 // Switch to the shared context in the worker thread
1063 glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1065 // Wait until all rendering calls for the shared context are executed
1066 glContextHelperAbstraction.WaitClient();
1068 // Must clear the context in the worker thread
1069 // Otherwise the shared context cannot be switched to from the render thread
1070 glContextHelperAbstraction.MakeContextNull();
1073 auto future = mImpl->threadPool->SubmitTask( 0u, workerFunction );
1076 mImpl->threadPool->Wait();
1078 // Clear the dependency list
1079 mImpl->textureDependencyList.Clear();
1085 if( instruction.mRenderTracker && instruction.mFrameBuffer )
1087 // This will create a sync object every frame this render tracker
1088 // is alive (though it should be now be created only for
1089 // render-once render tasks)
1090 instruction.mRenderTracker->CreateSyncObject( mImpl->glSyncAbstraction );
1091 instruction.mRenderTracker = nullptr; // Only create once.
1096 mImpl->currentContext->Flush();
1100 GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
1101 mImpl->currentContext->InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1105 void RenderManager::PostRender( bool uploadOnly )
1109 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
1111 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1114 GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
1115 mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1118 //Notify RenderGeometries that rendering has finished
1119 for ( auto&& iter : mImpl->geometryContainer )
1121 iter->OnRenderFinished();
1124 mImpl->UpdateTrackers();
1127 uint32_t count = 0u;
1128 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
1130 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
1133 const bool haveInstructions = count > 0u;
1135 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1136 mImpl->lastFrameWasRendered = haveInstructions;
1139 * The rendering has finished; swap to the next buffer.
1140 * Ideally the update has just finished using this buffer; otherwise the render thread
1141 * should block until the update has finished.
1143 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1145 DALI_PRINT_RENDER_END();
1148 } // namespace SceneGraph
1150 } // namespace Internal