[Tizen] Add screen and client rotation itself function
[platform/core/uifw/dali-core.git] / dali / internal / render / common / render-manager.cpp
1 /*
2  * Copyright (c) 2020 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/render/common/render-manager.h>
20
21 // EXTERNAL INCLUDES
22 #include <memory.h>
23
24 // INTERNAL INCLUDES
25 #include <dali/public-api/actors/sampling.h>
26 #include <dali/public-api/common/dali-common.h>
27 #include <dali/public-api/common/stage.h>
28 #include <dali/public-api/render-tasks/render-task.h>
29 #include <dali/devel-api/threading/thread-pool.h>
30 #include <dali/integration-api/debug.h>
31 #include <dali/integration-api/core.h>
32 #include <dali/integration-api/gl-context-helper-abstraction.h>
33 #include <dali/internal/common/owner-pointer.h>
34 #include <dali/internal/event/common/scene-impl.h>
35 #include <dali/internal/render/common/render-algorithms.h>
36 #include <dali/internal/render/common/render-debug.h>
37 #include <dali/internal/render/common/render-tracker.h>
38 #include <dali/internal/render/common/render-instruction-container.h>
39 #include <dali/internal/render/common/render-instruction.h>
40 #include <dali/internal/render/gl-resources/context.h>
41 #include <dali/internal/render/queue/render-queue.h>
42 #include <dali/internal/render/renderers/render-frame-buffer.h>
43 #include <dali/internal/render/renderers/render-geometry.h>
44 #include <dali/internal/render/renderers/render-renderer.h>
45 #include <dali/internal/render/renderers/render-sampler.h>
46 #include <dali/internal/render/shaders/program-controller.h>
47 #include <dali/internal/update/common/scene-graph-scene.h>
48
49 namespace Dali
50 {
51
52 namespace Internal
53 {
54
55 namespace SceneGraph
56 {
57
58 #if defined(DEBUG_ENABLED)
59 namespace
60 {
61 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER" );
62 } // unnamed namespace
63 #endif
64
65 /**
66  * Structure to contain internal data
67  */
68 struct RenderManager::Impl
69 {
70   Impl( Integration::GlAbstraction& glAbstraction,
71         Integration::GlSyncAbstraction& glSyncAbstraction,
72         Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
73         Integration::DepthBufferAvailable depthBufferAvailableParam,
74         Integration::StencilBufferAvailable stencilBufferAvailableParam )
75   : context( glAbstraction, &sceneContextContainer ),
76     currentContext( &context ),
77     glAbstraction( glAbstraction ),
78     glSyncAbstraction( glSyncAbstraction ),
79     glContextHelperAbstraction( glContextHelperAbstraction ),
80     renderQueue(),
81     renderAlgorithms(),
82     frameCount( 0u ),
83     renderBufferIndex( SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX ),
84     defaultSurfaceRect(),
85     rendererContainer(),
86     samplerContainer(),
87     textureContainer(),
88     frameBufferContainer(),
89     lastFrameWasRendered( false ),
90     programController( glAbstraction ),
91     depthBufferAvailable( depthBufferAvailableParam ),
92     stencilBufferAvailable( stencilBufferAvailableParam ),
93     defaultSurfaceOrientation( 0 )
94   {
95      // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
96     threadPool = std::unique_ptr<Dali::ThreadPool>( new Dali::ThreadPool() );
97     threadPool->Initialize( 1u );
98   }
99
100   ~Impl()
101   {
102     threadPool.reset( nullptr ); // reset now to maintain correct destruction order
103   }
104
105   void AddRenderTracker( Render::RenderTracker* renderTracker )
106   {
107     DALI_ASSERT_DEBUG( renderTracker != NULL );
108     mRenderTrackers.PushBack( renderTracker );
109   }
110
111   void RemoveRenderTracker( Render::RenderTracker* renderTracker )
112   {
113     mRenderTrackers.EraseObject( renderTracker );
114   }
115
116   Context* CreateSceneContext()
117   {
118     sceneContextContainer.push_back( new Context( glAbstraction ) );
119     return sceneContextContainer[ sceneContextContainer.size() - 1 ];
120   }
121
122   void DestroySceneContext( Context* sceneContext )
123   {
124     auto iter = std::find( sceneContextContainer.begin(), sceneContextContainer.end(), sceneContext );
125     if( iter != sceneContextContainer.end() )
126     {
127       sceneContextContainer.erase( iter );
128     }
129   }
130
131   Context* ReplaceSceneContext( Context* oldSceneContext )
132   {
133     Context* newContext = new Context( glAbstraction );
134     std::replace( sceneContextContainer.begin(), sceneContextContainer.end(), oldSceneContext, newContext );
135     return newContext;
136   }
137
138   void UpdateTrackers()
139   {
140     for( auto&& iter : mRenderTrackers )
141     {
142       iter->PollSyncObject();
143     }
144   }
145
146   // the order is important for destruction,
147   // programs are owned by context at the moment.
148   Context                                   context;                 ///< Holds the GL state of the share resource context
149   Context*                                  currentContext;          ///< Holds the GL state of the current context for rendering
150   std::vector< Context* >                   sceneContextContainer;   ///< List of owned contexts holding the GL state per scene
151   Integration::GlAbstraction&               glAbstraction;           ///< GL abstraction
152   Integration::GlSyncAbstraction&           glSyncAbstraction;       ///< GL sync abstraction
153   Integration::GlContextHelperAbstraction&  glContextHelperAbstraction; ///< GL context helper abstraction
154   RenderQueue                               renderQueue;             ///< A message queue for receiving messages from the update-thread.
155
156   std::vector< SceneGraph::Scene* >         sceneContainer;          ///< List of pointers to the scene graph objects of the scenes
157
158   Render::RenderAlgorithms                  renderAlgorithms;        ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
159
160   uint32_t                                  frameCount;              ///< The current frame count
161   BufferIndex                               renderBufferIndex;       ///< The index of the buffer to read from; this is opposite of the "update" buffer
162
163   Rect<int32_t>                             defaultSurfaceRect;      ///< Rectangle for the default surface we are rendering to
164
165   OwnerContainer< Render::Renderer* >       rendererContainer;       ///< List of owned renderers
166   OwnerContainer< Render::Sampler* >        samplerContainer;        ///< List of owned samplers
167   OwnerContainer< Render::Texture* >        textureContainer;        ///< List of owned textures
168   OwnerContainer< Render::FrameBuffer* >    frameBufferContainer;    ///< List of owned framebuffers
169   OwnerContainer< Render::PropertyBuffer* > propertyBufferContainer; ///< List of owned property buffers
170   OwnerContainer< Render::Geometry* >       geometryContainer;       ///< List of owned Geometries
171
172   bool                                      lastFrameWasRendered;    ///< Keeps track of the last frame being rendered due to having render instructions
173
174   OwnerContainer< Render::RenderTracker* >  mRenderTrackers;         ///< List of render trackers
175
176   ProgramController                         programController;        ///< Owner of the GL programs
177
178   Integration::DepthBufferAvailable         depthBufferAvailable;     ///< Whether the depth buffer is available
179   Integration::StencilBufferAvailable       stencilBufferAvailable;   ///< Whether the stencil buffer is available
180
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
185
186 };
187
188 RenderManager* RenderManager::New( Integration::GlAbstraction& glAbstraction,
189                                    Integration::GlSyncAbstraction& glSyncAbstraction,
190                                    Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
191                                    Integration::DepthBufferAvailable depthBufferAvailable,
192                                    Integration::StencilBufferAvailable stencilBufferAvailable )
193 {
194   RenderManager* manager = new RenderManager;
195   manager->mImpl = new Impl( glAbstraction,
196                              glSyncAbstraction,
197                              glContextHelperAbstraction,
198                              depthBufferAvailable,
199                              stencilBufferAvailable );
200   return manager;
201 }
202
203 RenderManager::RenderManager()
204 : mImpl(NULL)
205 {
206 }
207
208 RenderManager::~RenderManager()
209 {
210   delete mImpl;
211 }
212
213 RenderQueue& RenderManager::GetRenderQueue()
214 {
215   return mImpl->renderQueue;
216 }
217
218 void RenderManager::ContextCreated()
219 {
220   mImpl->context.GlContextCreated();
221   mImpl->programController.GlContextCreated();
222
223   // renderers, textures and gpu buffers cannot reinitialize themselves
224   // so they rely on someone reloading the data for them
225 }
226
227 void RenderManager::ContextDestroyed()
228 {
229   mImpl->context.GlContextDestroyed();
230   mImpl->programController.GlContextDestroyed();
231
232   //Inform textures
233   for( auto&& texture : mImpl->textureContainer )
234   {
235     texture->GlContextDestroyed();
236   }
237
238   //Inform framebuffers
239   for( auto&& framebuffer : mImpl->frameBufferContainer )
240   {
241     framebuffer->GlContextDestroyed();
242   }
243
244   // inform renderers
245   for( auto&& renderer : mImpl->rendererContainer )
246   {
247     renderer->GlContextDestroyed();
248   }
249
250   // inform scenes
251   for( auto&& scene : mImpl->sceneContainer )
252   {
253     scene->GlContextDestroyed();
254   }
255 }
256
257 void RenderManager::SetShaderSaver( ShaderSaver& upstream )
258 {
259   mImpl->programController.SetShaderSaver( upstream );
260 }
261
262 void RenderManager::SetDefaultSurfaceRect(const Rect<int32_t>& rect)
263 {
264   mImpl->defaultSurfaceRect = rect;
265 }
266
267 void RenderManager::SetDefaultSurfaceOrientation( int orientation )
268 {
269   mImpl->defaultSurfaceOrientation = orientation;
270 }
271
272 void RenderManager::AddRenderer( OwnerPointer< Render::Renderer >& renderer )
273 {
274   // Initialize the renderer as we are now in render thread
275   renderer->Initialize( mImpl->context );
276
277   mImpl->rendererContainer.PushBack( renderer.Release() );
278 }
279
280 void RenderManager::RemoveRenderer( Render::Renderer* renderer )
281 {
282   mImpl->rendererContainer.EraseObject( renderer );
283 }
284
285 void RenderManager::AddSampler( OwnerPointer< Render::Sampler >& sampler )
286 {
287   mImpl->samplerContainer.PushBack( sampler.Release() );
288 }
289
290 void RenderManager::RemoveSampler( Render::Sampler* sampler )
291 {
292   mImpl->samplerContainer.EraseObject( sampler );
293 }
294
295 void RenderManager::AddTexture( OwnerPointer< Render::Texture >& texture )
296 {
297   texture->Initialize( mImpl->context );
298   mImpl->textureContainer.PushBack( texture.Release() );
299 }
300
301 void RenderManager::RemoveTexture( Render::Texture* texture )
302 {
303   DALI_ASSERT_DEBUG( NULL != texture );
304
305   // Find the texture, use reference to pointer so we can do the erase safely
306   for ( auto&& iter : mImpl->textureContainer )
307   {
308     if ( iter == texture )
309     {
310       texture->Destroy( mImpl->context );
311       mImpl->textureContainer.Erase( &iter ); // Texture found; now destroy it
312       return;
313     }
314   }
315 }
316
317 void RenderManager::UploadTexture( Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params )
318 {
319   texture->Upload( mImpl->context, pixelData, params );
320 }
321
322 void RenderManager::GenerateMipmaps( Render::Texture* texture )
323 {
324   texture->GenerateMipmaps( mImpl->context );
325 }
326
327 void RenderManager::SetFilterMode( Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode )
328 {
329   sampler->mMinificationFilter = static_cast<Dali::FilterMode::Type>(minFilterMode);
330   sampler->mMagnificationFilter = static_cast<Dali::FilterMode::Type>(magFilterMode );
331 }
332
333 void RenderManager::SetWrapMode( Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode )
334 {
335   sampler->mRWrapMode = static_cast<Dali::WrapMode::Type>(rWrapMode);
336   sampler->mSWrapMode = static_cast<Dali::WrapMode::Type>(sWrapMode);
337   sampler->mTWrapMode = static_cast<Dali::WrapMode::Type>(tWrapMode);
338 }
339
340 void RenderManager::AddFrameBuffer( OwnerPointer< Render::FrameBuffer >& frameBuffer )
341 {
342   Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
343   mImpl->frameBufferContainer.PushBack( frameBufferPtr );
344   frameBufferPtr->Initialize( mImpl->context );
345 }
346
347 void RenderManager::RemoveFrameBuffer( Render::FrameBuffer* frameBuffer )
348 {
349   DALI_ASSERT_DEBUG( NULL != frameBuffer );
350
351   // Find the sampler, use reference so we can safely do the erase
352   for ( auto&& iter : mImpl->frameBufferContainer )
353   {
354     if ( iter == frameBuffer )
355     {
356       frameBuffer->Destroy( mImpl->context );
357       mImpl->frameBufferContainer.Erase( &iter ); // frameBuffer found; now destroy it
358
359       break;
360     }
361   }
362 }
363 void RenderManager::InitializeScene( SceneGraph::Scene* scene )
364 {
365   scene->Initialize( *mImpl->CreateSceneContext() );
366   mImpl->sceneContainer.push_back( scene );
367 }
368
369 void RenderManager::UninitializeScene( SceneGraph::Scene* scene )
370 {
371   mImpl->DestroySceneContext( scene->GetContext() );
372
373   auto iter = std::find( mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene );
374   if( iter != mImpl->sceneContainer.end() )
375   {
376     mImpl->sceneContainer.erase( iter );
377   }
378 }
379
380 void RenderManager::SurfaceReplaced( SceneGraph::Scene* scene )
381 {
382   Context* newContext = mImpl->ReplaceSceneContext( scene->GetContext() );
383   scene->Initialize( *newContext );
384 }
385
386 void RenderManager::AttachColorTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer )
387 {
388   frameBuffer->AttachColorTexture( mImpl->context, texture, mipmapLevel, layer );
389 }
390
391 void RenderManager::AttachDepthTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel )
392 {
393   frameBuffer->AttachDepthTexture( mImpl->context, texture, mipmapLevel );
394 }
395
396 void RenderManager::AttachDepthStencilTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel )
397 {
398   frameBuffer->AttachDepthStencilTexture( mImpl->context, texture, mipmapLevel );
399 }
400
401 void RenderManager::AddPropertyBuffer( OwnerPointer< Render::PropertyBuffer >& propertyBuffer )
402 {
403   mImpl->propertyBufferContainer.PushBack( propertyBuffer.Release() );
404 }
405
406 void RenderManager::RemovePropertyBuffer( Render::PropertyBuffer* propertyBuffer )
407 {
408   mImpl->propertyBufferContainer.EraseObject( propertyBuffer );
409 }
410
411 void RenderManager::SetPropertyBufferFormat( Render::PropertyBuffer* propertyBuffer, OwnerPointer< Render::PropertyBuffer::Format>& format )
412 {
413   propertyBuffer->SetFormat( format.Release() );
414 }
415
416 void RenderManager::SetPropertyBufferData( Render::PropertyBuffer* propertyBuffer, OwnerPointer< Vector<uint8_t> >& data, uint32_t size )
417 {
418   propertyBuffer->SetData( data.Release(), size );
419 }
420
421 void RenderManager::SetIndexBuffer( Render::Geometry* geometry, Dali::Vector<uint16_t>& indices )
422 {
423   geometry->SetIndexBuffer( indices );
424 }
425
426 void RenderManager::AddGeometry( OwnerPointer< Render::Geometry >& geometry )
427 {
428   mImpl->geometryContainer.PushBack( geometry.Release() );
429 }
430
431 void RenderManager::RemoveGeometry( Render::Geometry* geometry )
432 {
433   mImpl->geometryContainer.EraseObject( geometry );
434 }
435
436 void RenderManager::AttachVertexBuffer( Render::Geometry* geometry, Render::PropertyBuffer* propertyBuffer )
437 {
438   DALI_ASSERT_DEBUG( NULL != geometry );
439
440   // Find the geometry
441   for ( auto&& iter : mImpl->geometryContainer )
442   {
443     if ( iter == geometry )
444     {
445       iter->AddPropertyBuffer( propertyBuffer );
446       break;
447     }
448   }
449 }
450
451 void RenderManager::RemoveVertexBuffer( Render::Geometry* geometry, Render::PropertyBuffer* propertyBuffer )
452 {
453   DALI_ASSERT_DEBUG( NULL != geometry );
454
455   // Find the geometry
456   for ( auto&& iter : mImpl->geometryContainer )
457   {
458     if ( iter == geometry )
459     {
460       iter->RemovePropertyBuffer( propertyBuffer );
461       break;
462     }
463   }
464 }
465
466 void RenderManager::SetGeometryType( Render::Geometry* geometry, uint32_t geometryType )
467 {
468   geometry->SetType( Render::Geometry::Type(geometryType) );
469 }
470
471 void RenderManager::AddRenderTracker( Render::RenderTracker* renderTracker )
472 {
473   mImpl->AddRenderTracker(renderTracker);
474 }
475
476 void RenderManager::RemoveRenderTracker( Render::RenderTracker* renderTracker )
477 {
478   mImpl->RemoveRenderTracker(renderTracker);
479 }
480
481 ProgramCache* RenderManager::GetProgramCache()
482 {
483   return &(mImpl->programController);
484 }
485
486 void RenderManager::PreRender( Integration::RenderStatus& status, bool forceClear, bool uploadOnly )
487 {
488   DALI_PRINT_RENDER_START( mImpl->renderBufferIndex );
489
490   // Core::Render documents that GL context must be current before calling Render
491   DALI_ASSERT_DEBUG( mImpl->context.IsGlContextCreated() );
492
493   // Increment the frame count at the beginning of each frame
494   ++mImpl->frameCount;
495
496   // Process messages queued during previous update
497   mImpl->renderQueue.ProcessMessages( mImpl->renderBufferIndex );
498
499   uint32_t count = 0u;
500   for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
501   {
502     count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
503   }
504
505   const bool haveInstructions = count > 0u;
506
507   DALI_LOG_INFO( gLogFilter, Debug::General,
508                  "Render: haveInstructions(%s) || mImpl->lastFrameWasRendered(%s) || forceClear(%s)\n",
509                  haveInstructions ? "true" : "false",
510                  mImpl->lastFrameWasRendered ? "true" : "false",
511                  forceClear ? "true" : "false" );
512
513   // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
514   if( haveInstructions || mImpl->lastFrameWasRendered || forceClear )
515   {
516     DALI_LOG_INFO( gLogFilter, Debug::General, "Render: Processing\n" );
517
518     if ( !uploadOnly )
519     {
520       // Mark that we will require a post-render step to be performed (includes swap-buffers).
521       status.SetNeedsPostRender( true );
522     }
523
524     // Switch to the shared context
525     if ( mImpl->currentContext != &mImpl->context )
526     {
527       mImpl->currentContext = &mImpl->context;
528
529       if ( mImpl->currentContext->IsSurfacelessContextSupported() )
530       {
531         mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
532       }
533
534       // Clear the current cached program when the context is switched
535       mImpl->programController.ClearCurrentProgram();
536     }
537
538     // Upload the geometries
539     for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
540     {
541       RenderInstructionContainer& instructions = mImpl->sceneContainer[i]->GetRenderInstructions();
542       for ( uint32_t j = 0; j < instructions.Count( mImpl->renderBufferIndex ); ++j )
543       {
544         RenderInstruction& instruction = instructions.At( mImpl->renderBufferIndex, j );
545
546         const Matrix* viewMatrix       = instruction.GetViewMatrix( mImpl->renderBufferIndex );
547         const Matrix* projectionMatrix = instruction.GetProjectionMatrix( mImpl->renderBufferIndex );
548
549         DALI_ASSERT_DEBUG( viewMatrix );
550         DALI_ASSERT_DEBUG( projectionMatrix );
551
552         if( viewMatrix && projectionMatrix )
553         {
554           const RenderListContainer::SizeType renderListCount = instruction.RenderListCount();
555
556           // Iterate through each render list.
557           for( RenderListContainer::SizeType index = 0; index < renderListCount; ++index )
558           {
559             const RenderList* renderList = instruction.GetRenderList( index );
560
561             if( renderList && !renderList->IsEmpty() )
562             {
563               const std::size_t itemCount = renderList->Count();
564               for( uint32_t itemIndex = 0u; itemIndex < itemCount; ++itemIndex )
565               {
566                 const RenderItem& item = renderList->GetItem( itemIndex );
567                 if( DALI_LIKELY( item.mRenderer ) )
568                 {
569                   item.mRenderer->Upload( *mImpl->currentContext );
570                 }
571               }
572             }
573           }
574         }
575       }
576     }
577   }
578 }
579
580
581 void RenderManager::RenderScene( Integration::Scene& scene, bool renderToFbo )
582 {
583   Internal::Scene& sceneInternal = GetImplementation( scene );
584   SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
585
586   uint32_t count = sceneObject->GetRenderInstructions().Count( mImpl->renderBufferIndex );
587
588   for( uint32_t i = 0; i < count; ++i )
589   {
590     RenderInstruction& instruction = sceneObject->GetRenderInstructions().At( mImpl->renderBufferIndex, i );
591
592     if ( ( renderToFbo && !instruction.mFrameBuffer ) || ( !renderToFbo && instruction.mFrameBuffer ) )
593     {
594       continue; // skip
595     }
596
597     Rect<int32_t> viewportRect;
598     Vector4   clearColor;
599
600     if ( instruction.mIsClearColorSet )
601     {
602       clearColor = instruction.mClearColor;
603     }
604     else
605     {
606       clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
607     }
608
609     Rect<int32_t> surfaceRect = mImpl->defaultSurfaceRect;
610     Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
611     Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
612     int surfaceOrientation = mImpl->defaultSurfaceOrientation;
613
614     if ( instruction.mFrameBuffer )
615     {
616       // offscreen buffer
617       if ( mImpl->currentContext != &mImpl->context )
618       {
619         // Switch to shared context for off-screen buffer
620         mImpl->currentContext = &mImpl->context;
621
622         if ( mImpl->currentContext->IsSurfacelessContextSupported() )
623         {
624           mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
625         }
626
627         // Clear the current cached program when the context is switched
628         mImpl->programController.ClearCurrentProgram();
629       }
630     }
631     else
632     {
633       if ( mImpl->currentContext->IsSurfacelessContextSupported() )
634       {
635         if ( mImpl->currentContext != sceneObject->GetContext() )
636         {
637           // Switch the correct context if rendering to a surface
638           mImpl->currentContext = sceneObject->GetContext();
639
640           // Clear the current cached program when the context is switched
641           mImpl->programController.ClearCurrentProgram();
642         }
643       }
644
645       surfaceRect = Rect<int32_t>( 0, 0, static_cast<int32_t>( scene.GetSize().width ), static_cast<int32_t>( scene.GetSize().height ) );
646     }
647
648     DALI_ASSERT_DEBUG( mImpl->currentContext->IsGlContextCreated() );
649
650     // reset the program matrices for all programs once per frame
651     // this ensures we will set view and projection matrix once per program per camera
652     mImpl->programController.ResetProgramMatrices();
653
654     if( instruction.mFrameBuffer )
655     {
656       instruction.mFrameBuffer->Bind( *mImpl->currentContext );
657
658       // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
659       for (unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
660       {
661         mImpl->textureDependencyList.PushBack( instruction.mFrameBuffer->GetTextureId(i0) );
662       }
663     }
664     else
665     {
666       mImpl->currentContext->BindFramebuffer( GL_FRAMEBUFFER, 0u );
667     }
668
669     if ( !instruction.mFrameBuffer )
670     {
671       mImpl->currentContext->Viewport( surfaceRect.x,
672                                        surfaceRect.y,
673                                        surfaceRect.width,
674                                        surfaceRect.height );
675     }
676
677     // Clear the entire color, depth and stencil buffers for the default framebuffer, if required.
678     // It is important to clear all 3 buffers when they are being used, for performance on deferred renderers
679     // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
680     // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
681     GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
682
683     mImpl->currentContext->ColorMask( true );
684
685     if( depthBufferAvailable == Integration::DepthBufferAvailable::TRUE )
686     {
687       mImpl->currentContext->DepthMask( true );
688       clearMask |= GL_DEPTH_BUFFER_BIT;
689     }
690
691     if( stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
692     {
693       mImpl->currentContext->ClearStencil( 0 );
694       mImpl->currentContext->StencilMask( 0xFF ); // 8 bit stencil mask, all 1's
695       clearMask |= GL_STENCIL_BUFFER_BIT;
696     }
697
698     if( !instruction.mIgnoreRenderToFbo && ( instruction.mFrameBuffer != 0 ) )
699     {
700       // Offscreen buffer rendering
701       if ( instruction.mIsViewportSet )
702       {
703         // For glViewport the lower-left corner is (0,0)
704         const int32_t y = ( instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height ) - instruction.mViewport.y;
705         viewportRect.Set( instruction.mViewport.x,  y, instruction.mViewport.width, instruction.mViewport.height );
706       }
707       else
708       {
709         viewportRect.Set( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
710       }
711       surfaceOrientation = 0;
712     }
713     else // No Offscreen frame buffer rendering
714     {
715       // Check whether a viewport is specified, otherwise the full surface size is used
716       if ( instruction.mIsViewportSet )
717       {
718         // For glViewport the lower-left corner is (0,0)
719         const int32_t y = ( surfaceRect.height - instruction.mViewport.height ) - instruction.mViewport.y;
720         viewportRect.Set( instruction.mViewport.x,  y, instruction.mViewport.width, instruction.mViewport.height );
721       }
722       else
723       {
724         viewportRect = surfaceRect;
725       }
726     }
727
728     if( surfaceOrientation == 90 || surfaceOrientation == 270 )
729     {
730       int temp = viewportRect.width;
731       viewportRect.width = viewportRect.height;
732       viewportRect.height = temp;
733     }
734
735     bool clearFullFrameRect = true;
736     if( instruction.mFrameBuffer != 0 )
737     {
738       Viewport frameRect( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
739       clearFullFrameRect = ( frameRect == viewportRect );
740     }
741     else
742     {
743       clearFullFrameRect = ( surfaceRect == viewportRect );
744     }
745
746     mImpl->currentContext->Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
747
748     if( instruction.mIsClearColorSet )
749     {
750       mImpl->currentContext->ClearColor( clearColor.r,
751                                          clearColor.g,
752                                          clearColor.b,
753                                          clearColor.a );
754
755       if( !clearFullFrameRect )
756       {
757         mImpl->currentContext->SetScissorTest( true );
758         mImpl->currentContext->Scissor( viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height );
759         mImpl->currentContext->Clear( clearMask, Context::FORCE_CLEAR );
760         mImpl->currentContext->SetScissorTest( false );
761       }
762       else
763       {
764         mImpl->currentContext->SetScissorTest( false );
765         mImpl->currentContext->Clear( clearMask, Context::FORCE_CLEAR );
766       }
767     }
768
769     // Clear the list of bound textures
770     mImpl->boundTextures.Clear();
771
772     mImpl->renderAlgorithms.ProcessRenderInstruction(
773         instruction,
774         *mImpl->currentContext,
775         mImpl->renderBufferIndex,
776         depthBufferAvailable,
777         stencilBufferAvailable,
778         mImpl->boundTextures,
779         surfaceOrientation );
780
781     // Synchronise the FBO/Texture access when there are multiple contexts
782     if ( mImpl->currentContext->IsSurfacelessContextSupported() )
783     {
784       // Check whether any binded texture is in the dependency list
785       bool textureFound = false;
786
787       if ( mImpl->boundTextures.Count() > 0u && mImpl->textureDependencyList.Count() > 0u )
788       {
789         for ( auto textureId : mImpl->textureDependencyList )
790         {
791
792           textureFound = std::find_if( mImpl->boundTextures.Begin(), mImpl->boundTextures.End(),
793                                        [textureId]( GLuint id )
794                                        {
795                                          return textureId == id;
796                                        } ) != mImpl->boundTextures.End();
797         }
798       }
799
800       if ( textureFound )
801       {
802         if ( instruction.mFrameBuffer )
803         {
804           // For off-screen buffer
805
806           // Wait until all rendering calls for the currently context are executed
807           mImpl->glContextHelperAbstraction.WaitClient();
808
809           // Clear the dependency list
810           mImpl->textureDependencyList.Clear();
811         }
812         else
813         {
814           // Worker thread lambda function
815           auto& glContextHelperAbstraction = mImpl->glContextHelperAbstraction;
816           auto workerFunction = [&glContextHelperAbstraction]( int workerThread )
817           {
818             // Switch to the shared context in the worker thread
819             glContextHelperAbstraction.MakeSurfacelessContextCurrent();
820
821             // Wait until all rendering calls for the shared context are executed
822             glContextHelperAbstraction.WaitClient();
823
824             // Must clear the context in the worker thread
825             // Otherwise the shared context cannot be switched to from the render thread
826             glContextHelperAbstraction.MakeContextNull();
827           };
828
829           auto future = mImpl->threadPool->SubmitTask( 0u, workerFunction );
830           if ( future )
831           {
832             mImpl->threadPool->Wait();
833
834             // Clear the dependency list
835             mImpl->textureDependencyList.Clear();
836           }
837         }
838       }
839     }
840
841     if( instruction.mRenderTracker && instruction.mFrameBuffer )
842     {
843       // This will create a sync object every frame this render tracker
844       // is alive (though it should be now be created only for
845       // render-once render tasks)
846       instruction.mRenderTracker->CreateSyncObject( mImpl->glSyncAbstraction );
847       instruction.mRenderTracker = nullptr; // Only create once.
848     }
849
850     if ( renderToFbo )
851     {
852       mImpl->currentContext->Flush();
853     }
854   }
855
856   GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
857   mImpl->currentContext->InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
858 }
859
860 void RenderManager::PostRender( bool uploadOnly )
861 {
862   if ( !uploadOnly )
863   {
864     if ( mImpl->currentContext->IsSurfacelessContextSupported() )
865     {
866       mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
867     }
868
869     GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
870     mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
871   }
872
873   //Notify RenderGeometries that rendering has finished
874   for ( auto&& iter : mImpl->geometryContainer )
875   {
876     iter->OnRenderFinished();
877   }
878
879   mImpl->UpdateTrackers();
880
881
882   uint32_t count = 0u;
883   for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
884   {
885     count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
886   }
887
888   const bool haveInstructions = count > 0u;
889
890   // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
891   mImpl->lastFrameWasRendered = haveInstructions;
892
893   /**
894    * The rendering has finished; swap to the next buffer.
895    * Ideally the update has just finished using this buffer; otherwise the render thread
896    * should block until the update has finished.
897    */
898   mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
899
900   DALI_PRINT_RENDER_END();
901 }
902
903 } // namespace SceneGraph
904
905 } // namespace Internal
906
907 } // namespace Dali