[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::AddPropertyBuffer( OwnerPointer< Render::PropertyBuffer >& propertyBuffer )
392 {
393   mImpl->propertyBufferContainer.PushBack( propertyBuffer.Release() );
394 }
395
396 void RenderManager::RemovePropertyBuffer( Render::PropertyBuffer* propertyBuffer )
397 {
398   mImpl->propertyBufferContainer.EraseObject( propertyBuffer );
399 }
400
401 void RenderManager::SetPropertyBufferFormat( Render::PropertyBuffer* propertyBuffer, OwnerPointer< Render::PropertyBuffer::Format>& format )
402 {
403   propertyBuffer->SetFormat( format.Release() );
404 }
405
406 void RenderManager::SetPropertyBufferData( Render::PropertyBuffer* propertyBuffer, OwnerPointer< Vector<uint8_t> >& data, uint32_t size )
407 {
408   propertyBuffer->SetData( data.Release(), size );
409 }
410
411 void RenderManager::SetIndexBuffer( Render::Geometry* geometry, Dali::Vector<uint16_t>& indices )
412 {
413   geometry->SetIndexBuffer( indices );
414 }
415
416 void RenderManager::AddGeometry( OwnerPointer< Render::Geometry >& geometry )
417 {
418   mImpl->geometryContainer.PushBack( geometry.Release() );
419 }
420
421 void RenderManager::RemoveGeometry( Render::Geometry* geometry )
422 {
423   mImpl->geometryContainer.EraseObject( geometry );
424 }
425
426 void RenderManager::AttachVertexBuffer( Render::Geometry* geometry, Render::PropertyBuffer* propertyBuffer )
427 {
428   DALI_ASSERT_DEBUG( NULL != geometry );
429
430   // Find the geometry
431   for ( auto&& iter : mImpl->geometryContainer )
432   {
433     if ( iter == geometry )
434     {
435       iter->AddPropertyBuffer( propertyBuffer );
436       break;
437     }
438   }
439 }
440
441 void RenderManager::RemoveVertexBuffer( Render::Geometry* geometry, Render::PropertyBuffer* propertyBuffer )
442 {
443   DALI_ASSERT_DEBUG( NULL != geometry );
444
445   // Find the geometry
446   for ( auto&& iter : mImpl->geometryContainer )
447   {
448     if ( iter == geometry )
449     {
450       iter->RemovePropertyBuffer( propertyBuffer );
451       break;
452     }
453   }
454 }
455
456 void RenderManager::SetGeometryType( Render::Geometry* geometry, uint32_t geometryType )
457 {
458   geometry->SetType( Render::Geometry::Type(geometryType) );
459 }
460
461 void RenderManager::AddRenderTracker( Render::RenderTracker* renderTracker )
462 {
463   mImpl->AddRenderTracker(renderTracker);
464 }
465
466 void RenderManager::RemoveRenderTracker( Render::RenderTracker* renderTracker )
467 {
468   mImpl->RemoveRenderTracker(renderTracker);
469 }
470
471 ProgramCache* RenderManager::GetProgramCache()
472 {
473   return &(mImpl->programController);
474 }
475
476 void RenderManager::PreRender( Integration::RenderStatus& status, bool forceClear, bool uploadOnly )
477 {
478   DALI_PRINT_RENDER_START( mImpl->renderBufferIndex );
479
480   // Core::Render documents that GL context must be current before calling Render
481   DALI_ASSERT_DEBUG( mImpl->context.IsGlContextCreated() );
482
483   // Increment the frame count at the beginning of each frame
484   ++mImpl->frameCount;
485
486   // Process messages queued during previous update
487   mImpl->renderQueue.ProcessMessages( mImpl->renderBufferIndex );
488
489   uint32_t count = 0u;
490   for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
491   {
492     count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
493   }
494
495   const bool haveInstructions = count > 0u;
496
497   DALI_LOG_INFO( gLogFilter, Debug::General,
498                  "Render: haveInstructions(%s) || mImpl->lastFrameWasRendered(%s) || forceClear(%s)\n",
499                  haveInstructions ? "true" : "false",
500                  mImpl->lastFrameWasRendered ? "true" : "false",
501                  forceClear ? "true" : "false" );
502
503   // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
504   if( haveInstructions || mImpl->lastFrameWasRendered || forceClear )
505   {
506     DALI_LOG_INFO( gLogFilter, Debug::General, "Render: Processing\n" );
507
508     if ( !uploadOnly )
509     {
510       // Mark that we will require a post-render step to be performed (includes swap-buffers).
511       status.SetNeedsPostRender( true );
512     }
513
514     // Switch to the shared context
515     if ( mImpl->currentContext != &mImpl->context )
516     {
517       mImpl->currentContext = &mImpl->context;
518
519       if ( mImpl->currentContext->IsSurfacelessContextSupported() )
520       {
521         mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
522       }
523
524       // Clear the current cached program when the context is switched
525       mImpl->programController.ClearCurrentProgram();
526     }
527
528     // Upload the geometries
529     for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
530     {
531       RenderInstructionContainer& instructions = mImpl->sceneContainer[i]->GetRenderInstructions();
532       for ( uint32_t j = 0; j < instructions.Count( mImpl->renderBufferIndex ); ++j )
533       {
534         RenderInstruction& instruction = instructions.At( mImpl->renderBufferIndex, j );
535
536         const Matrix* viewMatrix       = instruction.GetViewMatrix( mImpl->renderBufferIndex );
537         const Matrix* projectionMatrix = instruction.GetProjectionMatrix( mImpl->renderBufferIndex );
538
539         DALI_ASSERT_DEBUG( viewMatrix );
540         DALI_ASSERT_DEBUG( projectionMatrix );
541
542         if( viewMatrix && projectionMatrix )
543         {
544           const RenderListContainer::SizeType renderListCount = instruction.RenderListCount();
545
546           // Iterate through each render list.
547           for( RenderListContainer::SizeType index = 0; index < renderListCount; ++index )
548           {
549             const RenderList* renderList = instruction.GetRenderList( index );
550
551             if( renderList && !renderList->IsEmpty() )
552             {
553               const std::size_t itemCount = renderList->Count();
554               for( uint32_t itemIndex = 0u; itemIndex < itemCount; ++itemIndex )
555               {
556                 const RenderItem& item = renderList->GetItem( itemIndex );
557                 if( DALI_LIKELY( item.mRenderer ) )
558                 {
559                   item.mRenderer->Upload( *mImpl->currentContext );
560                 }
561               }
562             }
563           }
564         }
565       }
566     }
567   }
568 }
569
570
571 void RenderManager::RenderScene( Integration::Scene& scene, bool renderToFbo )
572 {
573   Internal::Scene& sceneInternal = GetImplementation( scene );
574   SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
575
576   uint32_t count = sceneObject->GetRenderInstructions().Count( mImpl->renderBufferIndex );
577
578   for( uint32_t i = 0; i < count; ++i )
579   {
580     RenderInstruction& instruction = sceneObject->GetRenderInstructions().At( mImpl->renderBufferIndex, i );
581
582     if ( ( renderToFbo && !instruction.mFrameBuffer ) || ( !renderToFbo && instruction.mFrameBuffer ) )
583     {
584       continue; // skip
585     }
586
587     Rect<int32_t> viewportRect;
588     Vector4   clearColor;
589
590     if ( instruction.mIsClearColorSet )
591     {
592       clearColor = instruction.mClearColor;
593     }
594     else
595     {
596       clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
597     }
598
599     Rect<int32_t> surfaceRect = mImpl->defaultSurfaceRect;
600     Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
601     Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
602     int surfaceOrientation = mImpl->defaultSurfaceOrientation;
603
604     if ( instruction.mFrameBuffer )
605     {
606       // offscreen buffer
607       if ( mImpl->currentContext != &mImpl->context )
608       {
609         // Switch to shared context for off-screen buffer
610         mImpl->currentContext = &mImpl->context;
611
612         if ( mImpl->currentContext->IsSurfacelessContextSupported() )
613         {
614           mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
615         }
616
617         // Clear the current cached program when the context is switched
618         mImpl->programController.ClearCurrentProgram();
619       }
620     }
621     else
622     {
623       if ( mImpl->currentContext->IsSurfacelessContextSupported() )
624       {
625         if ( mImpl->currentContext != sceneObject->GetContext() )
626         {
627           // Switch the correct context if rendering to a surface
628           mImpl->currentContext = sceneObject->GetContext();
629
630           // Clear the current cached program when the context is switched
631           mImpl->programController.ClearCurrentProgram();
632         }
633       }
634
635       surfaceRect = Rect<int32_t>( 0, 0, static_cast<int32_t>( scene.GetSize().width ), static_cast<int32_t>( scene.GetSize().height ) );
636     }
637
638     DALI_ASSERT_DEBUG( mImpl->currentContext->IsGlContextCreated() );
639
640     // reset the program matrices for all programs once per frame
641     // this ensures we will set view and projection matrix once per program per camera
642     mImpl->programController.ResetProgramMatrices();
643
644     if( instruction.mFrameBuffer )
645     {
646       instruction.mFrameBuffer->Bind( *mImpl->currentContext );
647
648       // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
649       for (unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
650       {
651         mImpl->textureDependencyList.PushBack( instruction.mFrameBuffer->GetTextureId(i0) );
652       }
653     }
654     else
655     {
656       mImpl->currentContext->BindFramebuffer( GL_FRAMEBUFFER, 0u );
657     }
658
659     if ( !instruction.mFrameBuffer )
660     {
661       mImpl->currentContext->Viewport( surfaceRect.x,
662                                        surfaceRect.y,
663                                        surfaceRect.width,
664                                        surfaceRect.height );
665     }
666
667     // Clear the entire color, depth and stencil buffers for the default framebuffer, if required.
668     // It is important to clear all 3 buffers when they are being used, for performance on deferred renderers
669     // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
670     // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
671     GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
672
673     mImpl->currentContext->ColorMask( true );
674
675     if( depthBufferAvailable == Integration::DepthBufferAvailable::TRUE )
676     {
677       mImpl->currentContext->DepthMask( true );
678       clearMask |= GL_DEPTH_BUFFER_BIT;
679     }
680
681     if( stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
682     {
683       mImpl->currentContext->ClearStencil( 0 );
684       mImpl->currentContext->StencilMask( 0xFF ); // 8 bit stencil mask, all 1's
685       clearMask |= GL_STENCIL_BUFFER_BIT;
686     }
687
688     if( !instruction.mIgnoreRenderToFbo && ( instruction.mFrameBuffer != 0 ) )
689     {
690       // Offscreen buffer rendering
691       if ( instruction.mIsViewportSet )
692       {
693         // For glViewport the lower-left corner is (0,0)
694         const int32_t y = ( instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height ) - instruction.mViewport.y;
695         viewportRect.Set( instruction.mViewport.x,  y, instruction.mViewport.width, instruction.mViewport.height );
696       }
697       else
698       {
699         viewportRect.Set( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
700       }
701       surfaceOrientation = 0;
702     }
703     else // No Offscreen frame buffer rendering
704     {
705       // Check whether a viewport is specified, otherwise the full surface size is used
706       if ( instruction.mIsViewportSet )
707       {
708         // For glViewport the lower-left corner is (0,0)
709         const int32_t y = ( surfaceRect.height - instruction.mViewport.height ) - instruction.mViewport.y;
710         viewportRect.Set( instruction.mViewport.x,  y, instruction.mViewport.width, instruction.mViewport.height );
711       }
712       else
713       {
714         viewportRect = surfaceRect;
715       }
716     }
717
718     if( surfaceOrientation == 90 || surfaceOrientation == 270 )
719     {
720       int temp = viewportRect.width;
721       viewportRect.width = viewportRect.height;
722       viewportRect.height = temp;
723     }
724
725     bool clearFullFrameRect = true;
726     if( instruction.mFrameBuffer != 0 )
727     {
728       Viewport frameRect( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
729       clearFullFrameRect = ( frameRect == viewportRect );
730     }
731     else
732     {
733       clearFullFrameRect = ( surfaceRect == viewportRect );
734     }
735
736     mImpl->currentContext->Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
737
738     if( instruction.mIsClearColorSet )
739     {
740       mImpl->currentContext->ClearColor( clearColor.r,
741                                          clearColor.g,
742                                          clearColor.b,
743                                          clearColor.a );
744
745       if( !clearFullFrameRect )
746       {
747         mImpl->currentContext->SetScissorTest( true );
748         mImpl->currentContext->Scissor( viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height );
749         mImpl->currentContext->Clear( clearMask, Context::FORCE_CLEAR );
750         mImpl->currentContext->SetScissorTest( false );
751       }
752       else
753       {
754         mImpl->currentContext->SetScissorTest( false );
755         mImpl->currentContext->Clear( clearMask, Context::FORCE_CLEAR );
756       }
757     }
758
759     // Clear the list of bound textures
760     mImpl->boundTextures.Clear();
761
762     mImpl->renderAlgorithms.ProcessRenderInstruction(
763         instruction,
764         *mImpl->currentContext,
765         mImpl->renderBufferIndex,
766         depthBufferAvailable,
767         stencilBufferAvailable,
768         mImpl->boundTextures,
769         surfaceOrientation );
770
771     // Synchronise the FBO/Texture access when there are multiple contexts
772     if ( mImpl->currentContext->IsSurfacelessContextSupported() )
773     {
774       // Check whether any binded texture is in the dependency list
775       bool textureFound = false;
776
777       if ( mImpl->boundTextures.Count() > 0u && mImpl->textureDependencyList.Count() > 0u )
778       {
779         for ( auto textureId : mImpl->textureDependencyList )
780         {
781
782           textureFound = std::find_if( mImpl->boundTextures.Begin(), mImpl->boundTextures.End(),
783                                        [textureId]( GLuint id )
784                                        {
785                                          return textureId == id;
786                                        } ) != mImpl->boundTextures.End();
787         }
788       }
789
790       if ( textureFound )
791       {
792         if ( instruction.mFrameBuffer )
793         {
794           // For off-screen buffer
795
796           // Wait until all rendering calls for the currently context are executed
797           mImpl->glContextHelperAbstraction.WaitClient();
798
799           // Clear the dependency list
800           mImpl->textureDependencyList.Clear();
801         }
802         else
803         {
804           // Worker thread lambda function
805           auto& glContextHelperAbstraction = mImpl->glContextHelperAbstraction;
806           auto workerFunction = [&glContextHelperAbstraction]( int workerThread )
807           {
808             // Switch to the shared context in the worker thread
809             glContextHelperAbstraction.MakeSurfacelessContextCurrent();
810
811             // Wait until all rendering calls for the shared context are executed
812             glContextHelperAbstraction.WaitClient();
813
814             // Must clear the context in the worker thread
815             // Otherwise the shared context cannot be switched to from the render thread
816             glContextHelperAbstraction.MakeContextNull();
817           };
818
819           auto future = mImpl->threadPool->SubmitTask( 0u, workerFunction );
820           if ( future )
821           {
822             mImpl->threadPool->Wait();
823
824             // Clear the dependency list
825             mImpl->textureDependencyList.Clear();
826           }
827         }
828       }
829     }
830
831     if( instruction.mRenderTracker && instruction.mFrameBuffer )
832     {
833       // This will create a sync object every frame this render tracker
834       // is alive (though it should be now be created only for
835       // render-once render tasks)
836       instruction.mRenderTracker->CreateSyncObject( mImpl->glSyncAbstraction );
837       instruction.mRenderTracker = nullptr; // Only create once.
838     }
839
840     if ( renderToFbo )
841     {
842       mImpl->currentContext->Flush();
843     }
844   }
845
846   GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
847   mImpl->currentContext->InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
848 }
849
850 void RenderManager::PostRender( bool uploadOnly )
851 {
852   if ( !uploadOnly )
853   {
854     if ( mImpl->currentContext->IsSurfacelessContextSupported() )
855     {
856       mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
857     }
858
859     GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
860     mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
861   }
862
863   //Notify RenderGeometries that rendering has finished
864   for ( auto&& iter : mImpl->geometryContainer )
865   {
866     iter->OnRenderFinished();
867   }
868
869   mImpl->UpdateTrackers();
870
871
872   uint32_t count = 0u;
873   for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
874   {
875     count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
876   }
877
878   const bool haveInstructions = count > 0u;
879
880   // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
881   mImpl->lastFrameWasRendered = haveInstructions;
882
883   /**
884    * The rendering has finished; swap to the next buffer.
885    * Ideally the update has just finished using this buffer; otherwise the render thread
886    * should block until the update has finished.
887    */
888   mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
889
890   DALI_PRINT_RENDER_END();
891 }
892
893 } // namespace SceneGraph
894
895 } // namespace Internal
896
897 } // namespace Dali