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 );
108 //TODO: Need eglMakeCurrent first
109 context->GlContextCreated();
111 sceneContextContainer.PushBack( context );
115 void DestroySceneContext( Context* sceneContext )
117 auto iter = std::find( sceneContextContainer.Begin(), sceneContextContainer.End(), sceneContext );
118 if( iter != sceneContextContainer.End() )
120 ( *iter )->GlContextDestroyed();
121 sceneContextContainer.Erase( iter );
125 Context* ReplaceSceneContext( Context* oldSceneContext )
127 Context* newContext = new Context( glAbstraction );
129 oldSceneContext->GlContextDestroyed();
130 //TODO: Need eglMakeCurrent first
131 newContext->GlContextCreated();
133 std::replace( sceneContextContainer.begin(), sceneContextContainer.end(), oldSceneContext, newContext );
137 void UpdateTrackers()
139 for( auto&& iter : mRenderTrackers )
141 iter->PollSyncObject();
145 // the order is important for destruction,
146 // programs are owned by context at the moment.
147 Context context; ///< Holds the GL state of the share resource context
148 Context* currentContext; ///< Holds the GL state of the current context for rendering
149 OwnerContainer< Context* > sceneContextContainer; ///< List of owned contexts holding the GL state per scene
150 Integration::GlAbstraction& glAbstraction; ///< GL abstraction
151 Integration::GlSyncAbstraction& glSyncAbstraction; ///< GL sync abstraction
152 Integration::GlContextHelperAbstraction& glContextHelperAbstraction; ///< GL context helper abstraction
153 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
155 std::vector< SceneGraph::Scene* > sceneContainer; ///< List of pointers to the scene graph objects of the scenes
157 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
159 uint32_t frameCount; ///< The current frame count
160 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
162 Rect<int32_t> defaultSurfaceRect; ///< Rectangle for the default surface we are rendering to
164 OwnerContainer< Render::Renderer* > rendererContainer; ///< List of owned renderers
165 OwnerContainer< Render::Sampler* > samplerContainer; ///< List of owned samplers
166 OwnerContainer< Render::Texture* > textureContainer; ///< List of owned textures
167 OwnerContainer< Render::FrameBuffer* > frameBufferContainer; ///< List of owned framebuffers
168 OwnerContainer< Render::PropertyBuffer* > propertyBufferContainer; ///< List of owned property buffers
169 OwnerContainer< Render::Geometry* > geometryContainer; ///< List of owned Geometries
171 bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
173 OwnerContainer< Render::RenderTracker* > mRenderTrackers; ///< List of render trackers
175 ProgramController programController; ///< Owner of the GL programs
177 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
178 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
179 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
181 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
182 Vector<GLuint> boundTextures; ///< The textures bound for rendering
183 Vector<GLuint> textureDependencyList; ///< The dependency list of binded textures
184 int defaultSurfaceOrientation; ///< defaultSurfaceOrientation for the default surface we are rendering to
187 RenderManager* RenderManager::New( Integration::GlAbstraction& glAbstraction,
188 Integration::GlSyncAbstraction& glSyncAbstraction,
189 Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
190 Integration::DepthBufferAvailable depthBufferAvailable,
191 Integration::StencilBufferAvailable stencilBufferAvailable,
192 Integration::PartialUpdateAvailable partialUpdateAvailable )
194 RenderManager* manager = new RenderManager;
195 manager->mImpl = new Impl( glAbstraction,
197 glContextHelperAbstraction,
198 depthBufferAvailable,
199 stencilBufferAvailable,
200 partialUpdateAvailable );
204 RenderManager::RenderManager()
209 RenderManager::~RenderManager()
214 RenderQueue& RenderManager::GetRenderQueue()
216 return mImpl->renderQueue;
219 void RenderManager::ContextCreated()
221 mImpl->context.GlContextCreated();
222 mImpl->programController.GlContextCreated();
224 // renderers, textures and gpu buffers cannot reinitialize themselves
225 // so they rely on someone reloading the data for them
228 void RenderManager::ContextDestroyed()
230 mImpl->context.GlContextDestroyed();
231 mImpl->programController.GlContextDestroyed();
234 for( auto&& texture : mImpl->textureContainer )
236 texture->GlContextDestroyed();
239 //Inform framebuffers
240 for( auto&& framebuffer : mImpl->frameBufferContainer )
242 framebuffer->GlContextDestroyed();
246 for( auto&& renderer : mImpl->rendererContainer )
248 renderer->GlContextDestroyed();
252 for( auto&& context : mImpl->sceneContextContainer )
254 context->GlContextDestroyed();
258 void RenderManager::SetShaderSaver( ShaderSaver& upstream )
260 mImpl->programController.SetShaderSaver( upstream );
263 void RenderManager::SetDefaultSurfaceRect(const Rect<int32_t>& rect)
265 mImpl->defaultSurfaceRect = rect;
268 void RenderManager::SetDefaultSurfaceOrientation( int orientation )
270 mImpl->defaultSurfaceOrientation = orientation;
273 void RenderManager::AddRenderer( OwnerPointer< Render::Renderer >& renderer )
275 // Initialize the renderer as we are now in render thread
276 renderer->Initialize( mImpl->context );
278 mImpl->rendererContainer.PushBack( renderer.Release() );
281 void RenderManager::RemoveRenderer( Render::Renderer* renderer )
283 mImpl->rendererContainer.EraseObject( renderer );
286 void RenderManager::AddSampler( OwnerPointer< Render::Sampler >& sampler )
288 mImpl->samplerContainer.PushBack( sampler.Release() );
291 void RenderManager::RemoveSampler( Render::Sampler* sampler )
293 mImpl->samplerContainer.EraseObject( sampler );
296 void RenderManager::AddTexture( OwnerPointer< Render::Texture >& texture )
298 texture->Initialize( mImpl->context );
299 mImpl->textureContainer.PushBack( texture.Release() );
302 void RenderManager::RemoveTexture( Render::Texture* texture )
304 DALI_ASSERT_DEBUG( NULL != texture );
306 // Find the texture, use reference to pointer so we can do the erase safely
307 for ( auto&& iter : mImpl->textureContainer )
309 if ( iter == texture )
311 texture->Destroy( mImpl->context );
312 mImpl->textureContainer.Erase( &iter ); // Texture found; now destroy it
318 void RenderManager::UploadTexture( Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params )
320 texture->Upload( mImpl->context, pixelData, params );
323 void RenderManager::GenerateMipmaps( Render::Texture* texture )
325 texture->GenerateMipmaps( mImpl->context );
328 void RenderManager::SetFilterMode( Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode )
330 sampler->mMinificationFilter = static_cast<Dali::FilterMode::Type>(minFilterMode);
331 sampler->mMagnificationFilter = static_cast<Dali::FilterMode::Type>(magFilterMode );
334 void RenderManager::SetWrapMode( Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode )
336 sampler->mRWrapMode = static_cast<Dali::WrapMode::Type>(rWrapMode);
337 sampler->mSWrapMode = static_cast<Dali::WrapMode::Type>(sWrapMode);
338 sampler->mTWrapMode = static_cast<Dali::WrapMode::Type>(tWrapMode);
341 void RenderManager::AddFrameBuffer( OwnerPointer< Render::FrameBuffer >& frameBuffer )
343 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
344 mImpl->frameBufferContainer.PushBack( frameBufferPtr );
345 frameBufferPtr->Initialize( mImpl->context );
348 void RenderManager::RemoveFrameBuffer( Render::FrameBuffer* frameBuffer )
350 DALI_ASSERT_DEBUG( NULL != frameBuffer );
352 // Find the sampler, use reference so we can safely do the erase
353 for ( auto&& iter : mImpl->frameBufferContainer )
355 if ( iter == frameBuffer )
357 frameBuffer->Destroy( mImpl->context );
358 mImpl->frameBufferContainer.Erase( &iter ); // frameBuffer found; now destroy it
364 void RenderManager::InitializeScene( SceneGraph::Scene* scene )
366 scene->Initialize( *mImpl->CreateSceneContext() );
367 mImpl->sceneContainer.push_back( scene );
370 void RenderManager::UninitializeScene( SceneGraph::Scene* scene )
372 mImpl->DestroySceneContext( scene->GetContext() );
374 auto iter = std::find( mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene );
375 if( iter != mImpl->sceneContainer.end() )
377 mImpl->sceneContainer.erase( iter );
381 void RenderManager::SurfaceReplaced( SceneGraph::Scene* scene )
383 Context* newContext = mImpl->ReplaceSceneContext( scene->GetContext() );
384 scene->Initialize( *newContext );
387 void RenderManager::AttachColorTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer )
389 frameBuffer->AttachColorTexture( mImpl->context, texture, mipmapLevel, layer );
392 void RenderManager::AttachDepthTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel )
394 frameBuffer->AttachDepthTexture( mImpl->context, texture, mipmapLevel );
397 void RenderManager::AttachDepthStencilTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel )
399 frameBuffer->AttachDepthStencilTexture( mImpl->context, texture, mipmapLevel );
402 void RenderManager::AddPropertyBuffer( OwnerPointer< Render::PropertyBuffer >& propertyBuffer )
404 mImpl->propertyBufferContainer.PushBack( propertyBuffer.Release() );
407 void RenderManager::RemovePropertyBuffer( Render::PropertyBuffer* propertyBuffer )
409 mImpl->propertyBufferContainer.EraseObject( propertyBuffer );
412 void RenderManager::SetPropertyBufferFormat( Render::PropertyBuffer* propertyBuffer, OwnerPointer< Render::PropertyBuffer::Format>& format )
414 propertyBuffer->SetFormat( format.Release() );
417 void RenderManager::SetPropertyBufferData( Render::PropertyBuffer* propertyBuffer, OwnerPointer< Vector<uint8_t> >& data, uint32_t size )
419 propertyBuffer->SetData( data.Release(), size );
422 void RenderManager::SetIndexBuffer( Render::Geometry* geometry, Dali::Vector<uint16_t>& indices )
424 geometry->SetIndexBuffer( indices );
427 void RenderManager::AddGeometry( OwnerPointer< Render::Geometry >& geometry )
429 mImpl->geometryContainer.PushBack( geometry.Release() );
432 void RenderManager::RemoveGeometry( Render::Geometry* geometry )
434 mImpl->geometryContainer.EraseObject( geometry );
437 void RenderManager::AttachVertexBuffer( Render::Geometry* geometry, Render::PropertyBuffer* propertyBuffer )
439 DALI_ASSERT_DEBUG( NULL != geometry );
442 for ( auto&& iter : mImpl->geometryContainer )
444 if ( iter == geometry )
446 iter->AddPropertyBuffer( propertyBuffer );
452 void RenderManager::RemoveVertexBuffer( Render::Geometry* geometry, Render::PropertyBuffer* propertyBuffer )
454 DALI_ASSERT_DEBUG( NULL != geometry );
457 for ( auto&& iter : mImpl->geometryContainer )
459 if ( iter == geometry )
461 iter->RemovePropertyBuffer( propertyBuffer );
467 void RenderManager::SetGeometryType( Render::Geometry* geometry, uint32_t geometryType )
469 geometry->SetType( Render::Geometry::Type(geometryType) );
472 void RenderManager::AddRenderTracker( Render::RenderTracker* renderTracker )
474 mImpl->AddRenderTracker(renderTracker);
477 void RenderManager::RemoveRenderTracker( Render::RenderTracker* renderTracker )
479 mImpl->RemoveRenderTracker(renderTracker);
482 ProgramCache* RenderManager::GetProgramCache()
484 return &(mImpl->programController);
487 void RenderManager::PreRender( Integration::RenderStatus& status, bool forceClear, bool uploadOnly )
489 DALI_PRINT_RENDER_START( mImpl->renderBufferIndex );
491 // Core::Render documents that GL context must be current before calling Render
492 DALI_ASSERT_DEBUG( mImpl->context.IsGlContextCreated() );
494 // Increment the frame count at the beginning of each frame
497 // Process messages queued during previous update
498 mImpl->renderQueue.ProcessMessages( mImpl->renderBufferIndex );
501 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
503 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
506 const bool haveInstructions = count > 0u;
508 DALI_LOG_INFO( gLogFilter, Debug::General,
509 "Render: haveInstructions(%s) || mImpl->lastFrameWasRendered(%s) || forceClear(%s)\n",
510 haveInstructions ? "true" : "false",
511 mImpl->lastFrameWasRendered ? "true" : "false",
512 forceClear ? "true" : "false" );
514 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
515 if( haveInstructions || mImpl->lastFrameWasRendered || forceClear )
517 DALI_LOG_INFO( gLogFilter, Debug::General, "Render: Processing\n" );
519 // Switch to the shared context
520 if ( mImpl->currentContext != &mImpl->context )
522 mImpl->currentContext = &mImpl->context;
524 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
526 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
529 // Clear the current cached program when the context is switched
530 mImpl->programController.ClearCurrentProgram();
533 // Upload the geometries
534 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
536 RenderInstructionContainer& instructions = mImpl->sceneContainer[i]->GetRenderInstructions();
537 for ( uint32_t j = 0; j < instructions.Count( mImpl->renderBufferIndex ); ++j )
539 RenderInstruction& instruction = instructions.At( mImpl->renderBufferIndex, j );
541 const Matrix* viewMatrix = instruction.GetViewMatrix( mImpl->renderBufferIndex );
542 const Matrix* projectionMatrix = instruction.GetProjectionMatrix( mImpl->renderBufferIndex );
544 DALI_ASSERT_DEBUG( viewMatrix );
545 DALI_ASSERT_DEBUG( projectionMatrix );
547 if( viewMatrix && projectionMatrix )
549 const RenderListContainer::SizeType renderListCount = instruction.RenderListCount();
551 // Iterate through each render list.
552 for( RenderListContainer::SizeType index = 0; index < renderListCount; ++index )
554 const RenderList* renderList = instruction.GetRenderList( index );
556 if( renderList && !renderList->IsEmpty() )
558 const std::size_t itemCount = renderList->Count();
559 for( uint32_t itemIndex = 0u; itemIndex < itemCount; ++itemIndex )
561 const RenderItem& item = renderList->GetItem( itemIndex );
562 if( DALI_LIKELY( item.mRenderer ) )
564 item.mRenderer->Upload( *mImpl->currentContext );
575 void RenderManager::PreRender( Integration::Scene& scene, std::vector<Rect<int>>& damagedRects )
577 if (mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
582 // @TODO We need to do partial rendering rotation.
583 if( mImpl->defaultSurfaceOrientation != 0 )
588 class DamagedRectsCleaner
591 DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects)
592 : mDamagedRects(damagedRects),
597 void SetCleanOnReturn(bool cleanOnReturn)
599 mCleanOnReturn = cleanOnReturn;
602 ~DamagedRectsCleaner()
606 mDamagedRects.clear();
611 std::vector<Rect<int>>& mDamagedRects;
615 Rect<int32_t> surfaceRect = Rect<int32_t>(0, 0, static_cast<int32_t>( scene.GetSize().width ), static_cast<int32_t>( scene.GetSize().height ));
617 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
618 DamagedRectsCleaner damagedRectCleaner(damagedRects);
622 Internal::Scene& sceneInternal = GetImplementation(scene);
623 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
625 // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
626 // so you don't need to sort: std::stable_sort(itemsDirtyRects.begin(), itemsDirtyRects.end());
627 std::vector<DirtyRect>& itemsDirtyRects = sceneInternal.GetItemsDirtyRects();
628 for (DirtyRect& dirtyRect : itemsDirtyRects)
630 dirtyRect.visited = false;
633 uint32_t count = sceneObject->GetRenderInstructions().Count( mImpl->renderBufferIndex );
634 for (uint32_t i = 0; i < count; ++i)
636 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At( mImpl->renderBufferIndex, i );
638 if (instruction.mFrameBuffer)
640 return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
643 const Camera* camera = instruction.GetCamera();
644 if (camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
646 const Node* node = instruction.GetCamera()->GetNode();
651 Quaternion orientation;
652 node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
654 Vector3 orientationAxis;
655 Radian orientationAngle;
656 orientation.ToAxisAngle( orientationAxis, orientationAngle );
658 if (position.x > Math::MACHINE_EPSILON_10000 ||
659 position.y > Math::MACHINE_EPSILON_10000 ||
660 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
661 orientationAngle != ANGLE_180 ||
662 scale != Vector3(1.0f, 1.0f, 1.0f))
673 Rect<int32_t> viewportRect;
674 if (instruction.mIsViewportSet)
676 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
677 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
678 if (viewportRect.IsEmpty() || !viewportRect.IsValid())
680 return; // just skip funny use cases for now, empty viewport means it is set somewhere else
685 viewportRect = surfaceRect;
688 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
689 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
690 if (viewMatrix && projectionMatrix)
692 const RenderListContainer::SizeType count = instruction.RenderListCount();
693 for (RenderListContainer::SizeType index = 0u; index < count; ++index)
695 const RenderList* renderList = instruction.GetRenderList( index );
696 if (renderList && !renderList->IsEmpty())
698 const std::size_t count = renderList->Count();
699 for (uint32_t index = 0u; index < count; ++index)
701 RenderItem& item = renderList->GetItem( index );
702 // If the item does 3D transformation, do early exit and clean the damaged rect array
703 if (item.mUpdateSize == Vector3::ZERO)
709 DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
710 // If the item refers to updated node or renderer.
711 if (item.mIsUpdated ||
713 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
715 item.mIsUpdated = false;
716 item.mNode->SetUpdated(false);
718 rect = item.CalculateViewportSpaceAABB(item.mUpdateSize, viewportRect.width, viewportRect.height);
719 if (rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
721 const int left = rect.x;
722 const int top = rect.y;
723 const int right = rect.x + rect.width;
724 const int bottom = rect.y + rect.height;
725 rect.x = (left / 16) * 16;
726 rect.y = (top / 16) * 16;
727 rect.width = ((right + 16) / 16) * 16 - rect.x;
728 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
730 // Found valid dirty rect.
731 // 1. Insert it in the sorted array of the dirty rects.
732 // 2. Mark the related dirty rects as visited so they will not be removed below.
733 // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
734 dirtyRect.rect = rect;
735 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
736 dirtyRectPos = itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
739 while (++dirtyRectPos != itemsDirtyRects.end())
741 if (dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
746 dirtyRectPos->visited = true;
747 Rect<int>& dirtRect = dirtyRectPos->rect;
748 rect.Merge(dirtRect);
751 if (c > 3) // no more then 3 previous rects
753 itemsDirtyRects.erase(dirtyRectPos);
758 damagedRects.push_back(rect);
763 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
764 // 2. Mark the related dirty rects as visited so they will not be removed below.
765 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
766 while (dirtyRectPos != itemsDirtyRects.end())
768 if (dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
773 dirtyRectPos->visited = true;
783 // Check removed nodes or removed renderers dirty rects
784 auto i = itemsDirtyRects.begin();
785 auto j = itemsDirtyRects.begin();
786 while (i != itemsDirtyRects.end())
794 Rect<int>& dirtRect = i->rect;
795 damagedRects.push_back(dirtRect);
800 if( j != itemsDirtyRects.begin() )
802 itemsDirtyRects.resize(j - itemsDirtyRects.begin());
804 damagedRectCleaner.SetCleanOnReturn(false);
807 void RenderManager::RenderScene( Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo )
809 Rect<int> clippingRect;
810 RenderScene( status, scene, renderToFbo, clippingRect);
813 void RenderManager::RenderScene( Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect )
815 Internal::Scene& sceneInternal = GetImplementation( scene );
816 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
818 uint32_t count = sceneObject->GetRenderInstructions().Count( mImpl->renderBufferIndex );
820 for( uint32_t i = 0; i < count; ++i )
822 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At( mImpl->renderBufferIndex, i );
824 if ( ( renderToFbo && !instruction.mFrameBuffer ) || ( !renderToFbo && instruction.mFrameBuffer ) )
829 // Mark that we will require a post-render step to be performed (includes swap-buffers).
830 status.SetNeedsPostRender( true );
832 Rect<int32_t> viewportRect;
835 if ( instruction.mIsClearColorSet )
837 clearColor = instruction.mClearColor;
841 clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
844 Rect<int32_t> surfaceRect = mImpl->defaultSurfaceRect;
845 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
846 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
847 int surfaceOrientation = mImpl->defaultSurfaceOrientation;
849 if ( instruction.mFrameBuffer )
852 if ( mImpl->currentContext != &mImpl->context )
854 // Switch to shared context for off-screen buffer
855 mImpl->currentContext = &mImpl->context;
857 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
859 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
862 // Clear the current cached program when the context is switched
863 mImpl->programController.ClearCurrentProgram();
868 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
870 if ( mImpl->currentContext != sceneObject->GetContext() )
872 // Switch the correct context if rendering to a surface
873 mImpl->currentContext = sceneObject->GetContext();
875 // Clear the current cached program when the context is switched
876 mImpl->programController.ClearCurrentProgram();
880 surfaceRect = Rect<int32_t>( 0, 0, static_cast<int32_t>( scene.GetSize().width ), static_cast<int32_t>( scene.GetSize().height ) );
883 DALI_ASSERT_DEBUG( mImpl->currentContext->IsGlContextCreated() );
885 // reset the program matrices for all programs once per frame
886 // this ensures we will set view and projection matrix once per program per camera
887 mImpl->programController.ResetProgramMatrices();
889 if( instruction.mFrameBuffer )
891 instruction.mFrameBuffer->Bind( *mImpl->currentContext );
893 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
894 for (unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
896 mImpl->textureDependencyList.PushBack( instruction.mFrameBuffer->GetTextureId(i0) );
901 mImpl->currentContext->BindFramebuffer( GL_FRAMEBUFFER, 0u );
904 if ( !instruction.mFrameBuffer )
906 mImpl->currentContext->Viewport( surfaceRect.x,
909 surfaceRect.height );
912 // Clear the entire color, depth and stencil buffers for the default framebuffer, if required.
913 // It is important to clear all 3 buffers when they are being used, for performance on deferred renderers
914 // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
915 // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
916 GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
918 mImpl->currentContext->ColorMask( true );
920 if( depthBufferAvailable == Integration::DepthBufferAvailable::TRUE )
922 mImpl->currentContext->DepthMask( true );
923 clearMask |= GL_DEPTH_BUFFER_BIT;
926 if( stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
928 mImpl->currentContext->ClearStencil( 0 );
929 mImpl->currentContext->StencilMask( 0xFF ); // 8 bit stencil mask, all 1's
930 clearMask |= GL_STENCIL_BUFFER_BIT;
933 if( !instruction.mIgnoreRenderToFbo && ( instruction.mFrameBuffer != 0 ) )
935 // Offscreen buffer rendering
936 if ( instruction.mIsViewportSet )
938 // For glViewport the lower-left corner is (0,0)
939 const int32_t y = ( instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height ) - instruction.mViewport.y;
940 viewportRect.Set( instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height );
944 viewportRect.Set( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
946 surfaceOrientation = 0;
948 else // No Offscreen frame buffer rendering
950 // Check whether a viewport is specified, otherwise the full surface size is used
951 if ( instruction.mIsViewportSet )
953 // For glViewport the lower-left corner is (0,0)
954 const int32_t y = ( surfaceRect.height - instruction.mViewport.height ) - instruction.mViewport.y;
955 viewportRect.Set( instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height );
959 viewportRect = surfaceRect;
963 if( surfaceOrientation == 90 || surfaceOrientation == 270 )
965 int temp = viewportRect.width;
966 viewportRect.width = viewportRect.height;
967 viewportRect.height = temp;
970 bool clearFullFrameRect = true;
971 if( instruction.mFrameBuffer != 0 )
973 Viewport frameRect( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
974 clearFullFrameRect = ( frameRect == viewportRect );
978 clearFullFrameRect = ( surfaceRect == viewportRect );
981 if (!clippingRect.IsEmpty())
983 if (!clippingRect.Intersect(viewportRect))
985 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
986 clippingRect = Rect<int>();
988 clearFullFrameRect = false;
991 mImpl->currentContext->Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
993 if (instruction.mIsClearColorSet)
995 mImpl->currentContext->ClearColor(clearColor.r,
999 if (!clearFullFrameRect)
1001 if (!clippingRect.IsEmpty())
1003 mImpl->currentContext->SetScissorTest(true);
1004 mImpl->currentContext->Scissor(clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
1005 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
1006 mImpl->currentContext->SetScissorTest(false);
1010 mImpl->currentContext->SetScissorTest(true);
1011 mImpl->currentContext->Scissor(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
1012 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
1013 mImpl->currentContext->SetScissorTest(false);
1018 mImpl->currentContext->SetScissorTest(false);
1019 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
1023 // Clear the list of bound textures
1024 mImpl->boundTextures.Clear();
1026 mImpl->renderAlgorithms.ProcessRenderInstruction(
1028 *mImpl->currentContext,
1029 mImpl->renderBufferIndex,
1030 depthBufferAvailable,
1031 stencilBufferAvailable,
1032 mImpl->boundTextures,
1034 surfaceOrientation );
1036 // Synchronise the FBO/Texture access when there are multiple contexts
1037 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
1039 // Check whether any binded texture is in the dependency list
1040 bool textureFound = false;
1042 if ( mImpl->boundTextures.Count() > 0u && mImpl->textureDependencyList.Count() > 0u )
1044 for ( auto textureId : mImpl->textureDependencyList )
1047 textureFound = std::find_if( mImpl->boundTextures.Begin(), mImpl->boundTextures.End(),
1048 [textureId]( GLuint id )
1050 return textureId == id;
1051 } ) != mImpl->boundTextures.End();
1057 if ( instruction.mFrameBuffer )
1059 // For off-screen buffer
1061 // Wait until all rendering calls for the currently context are executed
1062 mImpl->glContextHelperAbstraction.WaitClient();
1064 // Clear the dependency list
1065 mImpl->textureDependencyList.Clear();
1069 // Worker thread lambda function
1070 auto& glContextHelperAbstraction = mImpl->glContextHelperAbstraction;
1071 auto workerFunction = [&glContextHelperAbstraction]( int workerThread )
1073 // Switch to the shared context in the worker thread
1074 glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1076 // Wait until all rendering calls for the shared context are executed
1077 glContextHelperAbstraction.WaitClient();
1079 // Must clear the context in the worker thread
1080 // Otherwise the shared context cannot be switched to from the render thread
1081 glContextHelperAbstraction.MakeContextNull();
1084 auto future = mImpl->threadPool->SubmitTask( 0u, workerFunction );
1087 mImpl->threadPool->Wait();
1089 // Clear the dependency list
1090 mImpl->textureDependencyList.Clear();
1096 if( instruction.mRenderTracker && instruction.mFrameBuffer )
1098 // This will create a sync object every frame this render tracker
1099 // is alive (though it should be now be created only for
1100 // render-once render tasks)
1101 instruction.mRenderTracker->CreateSyncObject( mImpl->glSyncAbstraction );
1102 instruction.mRenderTracker = nullptr; // Only create once.
1107 mImpl->currentContext->Flush();
1111 GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
1112 mImpl->currentContext->InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1115 void RenderManager::PostRender( bool uploadOnly )
1119 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
1121 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1124 GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
1125 mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1128 //Notify RenderGeometries that rendering has finished
1129 for ( auto&& iter : mImpl->geometryContainer )
1131 iter->OnRenderFinished();
1134 mImpl->UpdateTrackers();
1137 uint32_t count = 0u;
1138 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
1140 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
1143 const bool haveInstructions = count > 0u;
1145 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1146 mImpl->lastFrameWasRendered = haveInstructions;
1149 * The rendering has finished; swap to the next buffer.
1150 * Ideally the update has just finished using this buffer; otherwise the render thread
1151 * should block until the update has finished.
1153 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1155 DALI_PRINT_RENDER_END();
1158 } // namespace SceneGraph
1160 } // namespace Internal