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