Initial refactoring of graphics interface
[platform/core/uifw/dali-core.git] / dali / internal / render / common / render-manager.cpp
1 /*
2  * Copyright (c) 2021 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/devel-api/threading/thread-pool.h>
26 #include <dali/integration-api/core.h>
27 #include <dali/integration-api/gl-context-helper-abstraction.h>
28 #include <dali/internal/event/common/scene-impl.h>
29 #include <dali/internal/render/common/render-algorithms.h>
30 #include <dali/internal/render/common/render-debug.h>
31 #include <dali/internal/render/common/render-tracker.h>
32 #include <dali/internal/render/queue/render-queue.h>
33 #include <dali/internal/render/shaders/program-controller.h>
34
35 namespace Dali
36 {
37 namespace Internal
38 {
39 namespace SceneGraph
40 {
41 #if defined(DEBUG_ENABLED)
42 namespace
43 {
44 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER");
45 } // unnamed namespace
46 #endif
47
48 /**
49  * Structure to contain internal data
50  */
51 struct RenderManager::Impl
52 {
53   Impl(Graphics::Controller&               graphicsController,
54        Integration::DepthBufferAvailable   depthBufferAvailableParam,
55        Integration::StencilBufferAvailable stencilBufferAvailableParam,
56        Integration::PartialUpdateAvailable partialUpdateAvailableParam)
57   : context(graphicsController.GetGlAbstraction(), &sceneContextContainer),
58     currentContext(&context),
59     graphicsController(graphicsController),
60     renderQueue(),
61     renderAlgorithms(),
62     frameCount(0u),
63     renderBufferIndex(SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX),
64     defaultSurfaceRect(),
65     rendererContainer(),
66     samplerContainer(),
67     textureContainer(),
68     frameBufferContainer(),
69     lastFrameWasRendered(false),
70     programController(graphicsController),
71     depthBufferAvailable(depthBufferAvailableParam),
72     stencilBufferAvailable(stencilBufferAvailableParam),
73     partialUpdateAvailable(partialUpdateAvailableParam),
74     defaultSurfaceOrientation(0)
75   {
76     // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
77     threadPool = std::unique_ptr<Dali::ThreadPool>(new Dali::ThreadPool());
78     threadPool->Initialize(1u);
79   }
80
81   ~Impl()
82   {
83     threadPool.reset(nullptr); // reset now to maintain correct destruction order
84   }
85
86   void AddRenderTracker(Render::RenderTracker* renderTracker)
87   {
88     DALI_ASSERT_DEBUG(renderTracker != NULL);
89     mRenderTrackers.PushBack(renderTracker);
90   }
91
92   void RemoveRenderTracker(Render::RenderTracker* renderTracker)
93   {
94     mRenderTrackers.EraseObject(renderTracker);
95   }
96
97   Context* CreateSceneContext()
98   {
99     Context* context = new Context(graphicsController.GetGlAbstraction());
100     sceneContextContainer.PushBack(context);
101     return context;
102   }
103
104   void DestroySceneContext(Context* sceneContext)
105   {
106     auto iter = std::find(sceneContextContainer.Begin(), sceneContextContainer.End(), sceneContext);
107     if(iter != sceneContextContainer.End())
108     {
109       (*iter)->GlContextDestroyed();
110       sceneContextContainer.Erase(iter);
111     }
112   }
113
114   Context* ReplaceSceneContext(Context* oldSceneContext)
115   {
116     Context* newContext = new Context(graphicsController.GetGlAbstraction());
117
118     oldSceneContext->GlContextDestroyed();
119
120     std::replace(sceneContextContainer.begin(), sceneContextContainer.end(), oldSceneContext, newContext);
121     return newContext;
122   }
123
124   void UpdateTrackers()
125   {
126     for(auto&& iter : mRenderTrackers)
127     {
128       iter->PollSyncObject();
129     }
130   }
131
132   // the order is important for destruction,
133   // programs are owned by context at the moment.
134   Context                  context;               ///< Holds the GL state of the share resource context
135   Context*                 currentContext;        ///< Holds the GL state of the current context for rendering
136   OwnerContainer<Context*> sceneContextContainer; ///< List of owned contexts holding the GL state per scene
137   Graphics::Controller&    graphicsController;
138   RenderQueue              renderQueue; ///< A message queue for receiving messages from the update-thread.
139
140   std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
141
142   Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
143
144   uint32_t    frameCount;        ///< The current frame count
145   BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
146
147   Rect<int32_t> defaultSurfaceRect; ///< Rectangle for the default surface we are rendering to
148
149   OwnerContainer<Render::Renderer*>     rendererContainer;     ///< List of owned renderers
150   OwnerContainer<Render::Sampler*>      samplerContainer;      ///< List of owned samplers
151   OwnerContainer<Render::Texture*>      textureContainer;      ///< List of owned textures
152   OwnerContainer<Render::FrameBuffer*>  frameBufferContainer;  ///< List of owned framebuffers
153   OwnerContainer<Render::VertexBuffer*> vertexBufferContainer; ///< List of owned vertex buffers
154   OwnerContainer<Render::Geometry*>     geometryContainer;     ///< List of owned Geometries
155
156   bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
157
158   OwnerContainer<Render::RenderTracker*> mRenderTrackers; ///< List of render trackers
159
160   ProgramController programController; ///< Owner of the GL programs
161
162   Integration::DepthBufferAvailable   depthBufferAvailable;   ///< Whether the depth buffer is available
163   Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
164   Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
165
166   std::unique_ptr<Dali::ThreadPool> threadPool;            ///< The thread pool
167   Vector<GLuint>                    boundTextures;         ///< The textures bound for rendering
168   Vector<GLuint>                    textureDependencyList; ///< The dependency list of binded textures
169
170   int defaultSurfaceOrientation; ///< defaultSurfaceOrientation for the default surface we are rendering to
171 };
172
173 RenderManager* RenderManager::New(Graphics::Controller&               graphicsController,
174                                   Integration::DepthBufferAvailable   depthBufferAvailable,
175                                   Integration::StencilBufferAvailable stencilBufferAvailable,
176                                   Integration::PartialUpdateAvailable partialUpdateAvailable)
177 {
178   RenderManager* manager = new RenderManager;
179   manager->mImpl         = new Impl(graphicsController,
180                             depthBufferAvailable,
181                             stencilBufferAvailable,
182                             partialUpdateAvailable);
183   return manager;
184 }
185
186 RenderManager::RenderManager()
187 : mImpl(nullptr)
188 {
189 }
190
191 RenderManager::~RenderManager()
192 {
193   delete mImpl;
194 }
195
196 RenderQueue& RenderManager::GetRenderQueue()
197 {
198   return mImpl->renderQueue;
199 }
200
201 void RenderManager::ContextCreated()
202 {
203   mImpl->context.GlContextCreated();
204   mImpl->programController.GlContextCreated();
205
206   // renderers, textures and gpu buffers cannot reinitialize themselves
207   // so they rely on someone reloading the data for them
208 }
209
210 void RenderManager::ContextDestroyed()
211 {
212   mImpl->context.GlContextDestroyed();
213   mImpl->programController.GlContextDestroyed();
214
215   //Inform textures
216   for(auto&& texture : mImpl->textureContainer)
217   {
218     texture->GlContextDestroyed();
219   }
220
221   //Inform framebuffers
222   for(auto&& framebuffer : mImpl->frameBufferContainer)
223   {
224     framebuffer->GlContextDestroyed();
225   }
226
227   // inform renderers
228   for(auto&& renderer : mImpl->rendererContainer)
229   {
230     renderer->GlContextDestroyed();
231   }
232
233   // inform context
234   for(auto&& context : mImpl->sceneContextContainer)
235   {
236     context->GlContextDestroyed();
237   }
238 }
239
240 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
241 {
242   mImpl->programController.SetShaderSaver(upstream);
243 }
244
245 void RenderManager::SetDefaultSurfaceRect(const Rect<int32_t>& rect)
246 {
247   mImpl->defaultSurfaceRect = rect;
248 }
249
250 void RenderManager::SetDefaultSurfaceOrientation(int orientation)
251 {
252   mImpl->defaultSurfaceOrientation = orientation;
253 }
254
255 void RenderManager::AddRenderer(OwnerPointer<Render::Renderer>& renderer)
256 {
257   // Initialize the renderer as we are now in render thread
258   renderer->Initialize(mImpl->context);
259
260   mImpl->rendererContainer.PushBack(renderer.Release());
261 }
262
263 void RenderManager::RemoveRenderer(Render::Renderer* renderer)
264 {
265   mImpl->rendererContainer.EraseObject(renderer);
266 }
267
268 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
269 {
270   mImpl->samplerContainer.PushBack(sampler.Release());
271 }
272
273 void RenderManager::RemoveSampler(Render::Sampler* sampler)
274 {
275   mImpl->samplerContainer.EraseObject(sampler);
276 }
277
278 void RenderManager::AddTexture(OwnerPointer<Render::Texture>& texture)
279 {
280   texture->Initialize(mImpl->context);
281   mImpl->textureContainer.PushBack(texture.Release());
282 }
283
284 void RenderManager::RemoveTexture(Render::Texture* texture)
285 {
286   DALI_ASSERT_DEBUG(NULL != texture);
287
288   // Find the texture, use reference to pointer so we can do the erase safely
289   for(auto&& iter : mImpl->textureContainer)
290   {
291     if(iter == texture)
292     {
293       texture->Destroy(mImpl->context);
294       mImpl->textureContainer.Erase(&iter); // Texture found; now destroy it
295       return;
296     }
297   }
298 }
299
300 void RenderManager::UploadTexture(Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params)
301 {
302   texture->Upload(mImpl->context, pixelData, params);
303 }
304
305 void RenderManager::GenerateMipmaps(Render::Texture* texture)
306 {
307   texture->GenerateMipmaps(mImpl->context);
308 }
309
310 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
311 {
312   sampler->mMinificationFilter  = static_cast<Dali::FilterMode::Type>(minFilterMode);
313   sampler->mMagnificationFilter = static_cast<Dali::FilterMode::Type>(magFilterMode);
314 }
315
316 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
317 {
318   sampler->mRWrapMode = static_cast<Dali::WrapMode::Type>(rWrapMode);
319   sampler->mSWrapMode = static_cast<Dali::WrapMode::Type>(sWrapMode);
320   sampler->mTWrapMode = static_cast<Dali::WrapMode::Type>(tWrapMode);
321 }
322
323 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
324 {
325   Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
326   mImpl->frameBufferContainer.PushBack(frameBufferPtr);
327   frameBufferPtr->Initialize(mImpl->context);
328 }
329
330 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
331 {
332   DALI_ASSERT_DEBUG(NULL != frameBuffer);
333
334   // Find the sampler, use reference so we can safely do the erase
335   for(auto&& iter : mImpl->frameBufferContainer)
336   {
337     if(iter == frameBuffer)
338     {
339       frameBuffer->Destroy(mImpl->context);
340       mImpl->frameBufferContainer.Erase(&iter); // frameBuffer found; now destroy it
341
342       break;
343     }
344   }
345 }
346 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
347 {
348   scene->Initialize(*mImpl->CreateSceneContext());
349   mImpl->sceneContainer.push_back(scene);
350 }
351
352 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
353 {
354   mImpl->DestroySceneContext(scene->GetContext());
355
356   auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
357   if(iter != mImpl->sceneContainer.end())
358   {
359     mImpl->sceneContainer.erase(iter);
360   }
361 }
362
363 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
364 {
365   Context* newContext = mImpl->ReplaceSceneContext(scene->GetContext());
366   scene->Initialize(*newContext);
367 }
368
369 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
370 {
371   frameBuffer->AttachColorTexture(mImpl->context, texture, mipmapLevel, layer);
372 }
373
374 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
375 {
376   frameBuffer->AttachDepthTexture(mImpl->context, texture, mipmapLevel);
377 }
378
379 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
380 {
381   frameBuffer->AttachDepthStencilTexture(mImpl->context, texture, mipmapLevel);
382 }
383
384 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
385 {
386   mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
387 }
388
389 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
390 {
391   mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
392 }
393
394 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
395 {
396   vertexBuffer->SetFormat(format.Release());
397 }
398
399 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
400 {
401   vertexBuffer->SetData(data.Release(), size);
402 }
403
404 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Dali::Vector<uint16_t>& indices)
405 {
406   geometry->SetIndexBuffer(indices);
407 }
408
409 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
410 {
411   mImpl->geometryContainer.PushBack(geometry.Release());
412 }
413
414 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
415 {
416   mImpl->geometryContainer.EraseObject(geometry);
417 }
418
419 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
420 {
421   DALI_ASSERT_DEBUG(NULL != geometry);
422
423   // Find the geometry
424   for(auto&& iter : mImpl->geometryContainer)
425   {
426     if(iter == geometry)
427     {
428       iter->AddVertexBuffer(vertexBuffer);
429       break;
430     }
431   }
432 }
433
434 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
435 {
436   DALI_ASSERT_DEBUG(NULL != geometry);
437
438   // Find the geometry
439   for(auto&& iter : mImpl->geometryContainer)
440   {
441     if(iter == geometry)
442     {
443       iter->RemoveVertexBuffer(vertexBuffer);
444       break;
445     }
446   }
447 }
448
449 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
450 {
451   geometry->SetType(Render::Geometry::Type(geometryType));
452 }
453
454 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
455 {
456   mImpl->AddRenderTracker(renderTracker);
457 }
458
459 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
460 {
461   mImpl->RemoveRenderTracker(renderTracker);
462 }
463
464 ProgramCache* RenderManager::GetProgramCache()
465 {
466   return &(mImpl->programController);
467 }
468
469 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear, bool uploadOnly)
470 {
471   DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
472
473   // Core::Render documents that GL context must be current before calling Render
474   DALI_ASSERT_DEBUG(mImpl->context.IsGlContextCreated());
475
476   // Increment the frame count at the beginning of each frame
477   ++mImpl->frameCount;
478
479   // Process messages queued during previous update
480   mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
481
482   uint32_t count = 0u;
483   for(uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i)
484   {
485     count += mImpl->sceneContainer[i]->GetRenderInstructions().Count(mImpl->renderBufferIndex);
486   }
487
488   const bool haveInstructions = count > 0u;
489
490   DALI_LOG_INFO(gLogFilter, Debug::General, "Render: haveInstructions(%s) || mImpl->lastFrameWasRendered(%s) || forceClear(%s)\n", haveInstructions ? "true" : "false", mImpl->lastFrameWasRendered ? "true" : "false", forceClear ? "true" : "false");
491
492   // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
493   if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
494   {
495     DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
496
497     // Switch to the shared context
498     if(mImpl->currentContext != &mImpl->context)
499     {
500       mImpl->currentContext = &mImpl->context;
501
502       if(mImpl->currentContext->IsSurfacelessContextSupported())
503       {
504         mImpl->graphicsController.GetGlContextHelperAbstraction().MakeSurfacelessContextCurrent();
505       }
506
507       // Clear the current cached program when the context is switched
508       mImpl->programController.ClearCurrentProgram();
509     }
510
511     // Upload the geometries
512     for(uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i)
513     {
514       RenderInstructionContainer& instructions = mImpl->sceneContainer[i]->GetRenderInstructions();
515       for(uint32_t j = 0; j < instructions.Count(mImpl->renderBufferIndex); ++j)
516       {
517         RenderInstruction& instruction = instructions.At(mImpl->renderBufferIndex, j);
518
519         const Matrix* viewMatrix       = instruction.GetViewMatrix(mImpl->renderBufferIndex);
520         const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
521
522         DALI_ASSERT_DEBUG(viewMatrix);
523         DALI_ASSERT_DEBUG(projectionMatrix);
524
525         if(viewMatrix && projectionMatrix)
526         {
527           const RenderListContainer::SizeType renderListCount = instruction.RenderListCount();
528
529           // Iterate through each render list.
530           for(RenderListContainer::SizeType index = 0; index < renderListCount; ++index)
531           {
532             const RenderList* renderList = instruction.GetRenderList(index);
533
534             if(renderList && !renderList->IsEmpty())
535             {
536               const std::size_t itemCount = renderList->Count();
537               for(uint32_t itemIndex = 0u; itemIndex < itemCount; ++itemIndex)
538               {
539                 const RenderItem& item = renderList->GetItem(itemIndex);
540                 if(DALI_LIKELY(item.mRenderer))
541                 {
542                   item.mRenderer->Upload(*mImpl->currentContext);
543                 }
544               }
545             }
546           }
547         }
548       }
549     }
550   }
551 }
552
553 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
554 {
555   if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
556   {
557     return;
558   }
559
560   Internal::Scene&   sceneInternal = GetImplementation(scene);
561   SceneGraph::Scene* sceneObject   = sceneInternal.GetSceneObject();
562
563   if(sceneObject->IsRenderingSkipped())
564   {
565     // We don't need to calculate dirty rects
566     return;
567   }
568
569   class DamagedRectsCleaner
570   {
571   public:
572     DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects)
573     : mDamagedRects(damagedRects),
574       mCleanOnReturn(true)
575     {
576     }
577
578     void SetCleanOnReturn(bool cleanOnReturn)
579     {
580       mCleanOnReturn = cleanOnReturn;
581     }
582
583     ~DamagedRectsCleaner()
584     {
585       if(mCleanOnReturn)
586       {
587         mDamagedRects.clear();
588       }
589     }
590
591   private:
592     std::vector<Rect<int>>& mDamagedRects;
593     bool                    mCleanOnReturn;
594   };
595
596   Rect<int32_t> surfaceRect = Rect<int32_t>(0, 0, static_cast<int32_t>(scene.GetSize().width), static_cast<int32_t>(scene.GetSize().height));
597
598   // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
599   DamagedRectsCleaner damagedRectCleaner(damagedRects);
600
601   // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
602   // so you don't need to sort: std::stable_sort(itemsDirtyRects.begin(), itemsDirtyRects.end());
603   std::vector<DirtyRect>& itemsDirtyRects = sceneInternal.GetItemsDirtyRects();
604   for(DirtyRect& dirtyRect : itemsDirtyRects)
605   {
606     dirtyRect.visited = false;
607   }
608
609   uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
610   for(uint32_t i = 0; i < count; ++i)
611   {
612     RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
613
614     if(instruction.mFrameBuffer)
615     {
616       return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
617     }
618
619     const Camera* camera = instruction.GetCamera();
620     if(camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
621     {
622       const Node* node = instruction.GetCamera()->GetNode();
623       if(node)
624       {
625         Vector3    position;
626         Vector3    scale;
627         Quaternion orientation;
628         node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
629
630         Vector3 orientationAxis;
631         Radian  orientationAngle;
632         orientation.ToAxisAngle(orientationAxis, orientationAngle);
633
634         if(position.x > Math::MACHINE_EPSILON_10000 ||
635            position.y > Math::MACHINE_EPSILON_10000 ||
636            orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
637            orientationAngle != ANGLE_180 ||
638            scale != Vector3(1.0f, 1.0f, 1.0f))
639         {
640           return;
641         }
642       }
643     }
644     else
645     {
646       return;
647     }
648
649     Rect<int32_t> viewportRect;
650     if(instruction.mIsViewportSet)
651     {
652       const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
653       viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
654       if(viewportRect.IsEmpty() || !viewportRect.IsValid())
655       {
656         return; // just skip funny use cases for now, empty viewport means it is set somewhere else
657       }
658     }
659     else
660     {
661       viewportRect = surfaceRect;
662     }
663
664     const Matrix* viewMatrix       = instruction.GetViewMatrix(mImpl->renderBufferIndex);
665     const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
666     if(viewMatrix && projectionMatrix)
667     {
668       const RenderListContainer::SizeType count = instruction.RenderListCount();
669       for(RenderListContainer::SizeType index = 0u; index < count; ++index)
670       {
671         const RenderList* renderList = instruction.GetRenderList(index);
672         if(renderList && !renderList->IsEmpty())
673         {
674           const std::size_t count = renderList->Count();
675           for(uint32_t index = 0u; index < count; ++index)
676           {
677             RenderItem& item = renderList->GetItem(index);
678             // If the item does 3D transformation, do early exit and clean the damaged rect array
679             if(item.mUpdateSize == Vector3::ZERO)
680             {
681               return;
682             }
683
684             Rect<int> rect;
685             DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
686             // If the item refers to updated node or renderer.
687             if(item.mIsUpdated ||
688                (item.mNode &&
689                 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
690             {
691               item.mIsUpdated = false;
692               item.mNode->SetUpdated(false);
693
694               rect = item.CalculateViewportSpaceAABB(item.mUpdateSize, viewportRect.width, viewportRect.height);
695               if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
696               {
697                 const int left   = rect.x;
698                 const int top    = rect.y;
699                 const int right  = rect.x + rect.width;
700                 const int bottom = rect.y + rect.height;
701                 rect.x           = (left / 16) * 16;
702                 rect.y           = (top / 16) * 16;
703                 rect.width       = ((right + 16) / 16) * 16 - rect.x;
704                 rect.height      = ((bottom + 16) / 16) * 16 - rect.y;
705
706                 // Found valid dirty rect.
707                 // 1. Insert it in the sorted array of the dirty rects.
708                 // 2. Mark the related dirty rects as visited so they will not be removed below.
709                 // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
710                 dirtyRect.rect    = rect;
711                 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
712                 dirtyRectPos      = itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
713
714                 int c = 1;
715                 while(++dirtyRectPos != itemsDirtyRects.end())
716                 {
717                   if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
718                   {
719                     break;
720                   }
721
722                   dirtyRectPos->visited = true;
723                   Rect<int>& dirtRect   = dirtyRectPos->rect;
724                   rect.Merge(dirtRect);
725
726                   c++;
727                   if(c > 3) // no more then 3 previous rects
728                   {
729                     itemsDirtyRects.erase(dirtyRectPos);
730                     break;
731                   }
732                 }
733
734                 damagedRects.push_back(rect);
735               }
736             }
737             else
738             {
739               // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
740               // 2. Mark the related dirty rects as visited so they will not be removed below.
741               auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
742               while(dirtyRectPos != itemsDirtyRects.end())
743               {
744                 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
745                 {
746                   break;
747                 }
748
749                 dirtyRectPos->visited = true;
750                 dirtyRectPos++;
751               }
752             }
753           }
754         }
755       }
756     }
757   }
758
759   // Check removed nodes or removed renderers dirty rects
760   auto i = itemsDirtyRects.begin();
761   auto j = itemsDirtyRects.begin();
762   while(i != itemsDirtyRects.end())
763   {
764     if(i->visited)
765     {
766       *j++ = *i;
767     }
768     else
769     {
770       Rect<int>& dirtRect = i->rect;
771       damagedRects.push_back(dirtRect);
772     }
773     i++;
774   }
775
776   itemsDirtyRects.resize(j - itemsDirtyRects.begin());
777   damagedRectCleaner.SetCleanOnReturn(false);
778 }
779
780 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
781 {
782   Rect<int> clippingRect;
783   RenderScene(status, scene, renderToFbo, clippingRect);
784 }
785
786 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
787 {
788   Internal::Scene&   sceneInternal = GetImplementation(scene);
789   SceneGraph::Scene* sceneObject   = sceneInternal.GetSceneObject();
790
791   uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
792
793   for(uint32_t i = 0; i < count; ++i)
794   {
795     RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
796
797     if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
798     {
799       continue; // skip
800     }
801
802     // Mark that we will require a post-render step to be performed (includes swap-buffers).
803     status.SetNeedsPostRender(true);
804
805     Rect<int32_t> viewportRect;
806     Vector4       clearColor;
807
808     if(instruction.mIsClearColorSet)
809     {
810       clearColor = instruction.mClearColor;
811     }
812     else
813     {
814       clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
815     }
816
817     Rect<int32_t>                       surfaceRect            = mImpl->defaultSurfaceRect;
818     Integration::DepthBufferAvailable   depthBufferAvailable   = mImpl->depthBufferAvailable;
819     Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
820     int                                 surfaceOrientation     = sceneInternal.GetSurfaceOrientation();
821
822     if(instruction.mFrameBuffer)
823     {
824       // offscreen buffer
825       if(mImpl->currentContext != &mImpl->context)
826       {
827         // Switch to shared context for off-screen buffer
828         mImpl->currentContext = &mImpl->context;
829
830         if(mImpl->currentContext->IsSurfacelessContextSupported())
831         {
832           mImpl->graphicsController.GetGlContextHelperAbstraction().MakeSurfacelessContextCurrent();
833         }
834
835         // Clear the current cached program when the context is switched
836         mImpl->programController.ClearCurrentProgram();
837       }
838     }
839     else
840     {
841       if(mImpl->currentContext->IsSurfacelessContextSupported())
842       {
843         if(mImpl->currentContext != sceneObject->GetContext())
844         {
845           // Switch the correct context if rendering to a surface
846           mImpl->currentContext = sceneObject->GetContext();
847
848           // Clear the current cached program when the context is switched
849           mImpl->programController.ClearCurrentProgram();
850         }
851       }
852
853       surfaceRect = Rect<int32_t>(0, 0, static_cast<int32_t>(scene.GetSize().width), static_cast<int32_t>(scene.GetSize().height));
854     }
855
856     // Make sure that GL context must be created
857     mImpl->currentContext->GlContextCreated();
858
859     // reset the program matrices for all programs once per frame
860     // this ensures we will set view and projection matrix once per program per camera
861     mImpl->programController.ResetProgramMatrices();
862
863     if(instruction.mFrameBuffer)
864     {
865       instruction.mFrameBuffer->Bind(*mImpl->currentContext);
866
867       // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
868       for(unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
869       {
870         mImpl->textureDependencyList.PushBack(instruction.mFrameBuffer->GetTextureId(i0));
871       }
872     }
873     else
874     {
875       mImpl->currentContext->BindFramebuffer(GL_FRAMEBUFFER, 0u);
876     }
877
878     if(!instruction.mFrameBuffer)
879     {
880       mImpl->currentContext->Viewport(surfaceRect.x,
881                                       surfaceRect.y,
882                                       surfaceRect.width,
883                                       surfaceRect.height);
884     }
885
886     // Clear the entire color, depth and stencil buffers for the default framebuffer, if required.
887     // It is important to clear all 3 buffers when they are being used, for performance on deferred renderers
888     // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
889     // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
890     GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
891
892     mImpl->currentContext->ColorMask(true);
893
894     if(depthBufferAvailable == Integration::DepthBufferAvailable::TRUE)
895     {
896       mImpl->currentContext->DepthMask(true);
897       clearMask |= GL_DEPTH_BUFFER_BIT;
898     }
899
900     if(stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
901     {
902       mImpl->currentContext->ClearStencil(0);
903       mImpl->currentContext->StencilMask(0xFF); // 8 bit stencil mask, all 1's
904       clearMask |= GL_STENCIL_BUFFER_BIT;
905     }
906
907     if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
908     {
909       // Offscreen buffer rendering
910       if(instruction.mIsViewportSet)
911       {
912         // For glViewport the lower-left corner is (0,0)
913         const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
914         viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
915       }
916       else
917       {
918         viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
919       }
920       surfaceOrientation = 0;
921     }
922     else // No Offscreen frame buffer rendering
923     {
924       // Check whether a viewport is specified, otherwise the full surface size is used
925       if(instruction.mIsViewportSet)
926       {
927         // For glViewport the lower-left corner is (0,0)
928         const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
929         viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
930       }
931       else
932       {
933         viewportRect = surfaceRect;
934       }
935     }
936
937     // Set surface orientation
938     mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
939
940     bool clearFullFrameRect = true;
941     if(instruction.mFrameBuffer != nullptr)
942     {
943       Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
944       clearFullFrameRect = (frameRect == viewportRect);
945     }
946     else
947     {
948       clearFullFrameRect = (surfaceRect == viewportRect);
949     }
950
951     if(!clippingRect.IsEmpty())
952     {
953       if(!clippingRect.Intersect(viewportRect))
954       {
955         DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
956         clippingRect = Rect<int>();
957       }
958       clearFullFrameRect = false;
959     }
960
961     mImpl->currentContext->Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
962
963     if(instruction.mIsClearColorSet)
964     {
965       mImpl->currentContext->ClearColor(clearColor.r,
966                                         clearColor.g,
967                                         clearColor.b,
968                                         clearColor.a);
969       if(!clearFullFrameRect)
970       {
971         if(!clippingRect.IsEmpty())
972         {
973           mImpl->currentContext->SetScissorTest(true);
974           mImpl->currentContext->Scissor(clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
975           mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
976           mImpl->currentContext->SetScissorTest(false);
977         }
978         else
979         {
980           mImpl->currentContext->SetScissorTest(true);
981           mImpl->currentContext->Scissor(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
982           mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
983           mImpl->currentContext->SetScissorTest(false);
984         }
985       }
986       else
987       {
988         mImpl->currentContext->SetScissorTest(false);
989         mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
990       }
991     }
992
993     // Clear the list of bound textures
994     mImpl->boundTextures.Clear();
995
996     mImpl->renderAlgorithms.ProcessRenderInstruction(
997       instruction,
998       *mImpl->currentContext,
999       mImpl->renderBufferIndex,
1000       depthBufferAvailable,
1001       stencilBufferAvailable,
1002       mImpl->boundTextures,
1003       clippingRect);
1004
1005     // Synchronise the FBO/Texture access when there are multiple contexts
1006     if(mImpl->currentContext->IsSurfacelessContextSupported())
1007     {
1008       // Check whether any binded texture is in the dependency list
1009       bool textureFound = false;
1010
1011       if(mImpl->boundTextures.Count() > 0u && mImpl->textureDependencyList.Count() > 0u)
1012       {
1013         for(auto textureId : mImpl->textureDependencyList)
1014         {
1015           textureFound = std::find_if(mImpl->boundTextures.Begin(), mImpl->boundTextures.End(), [textureId](GLuint id) {
1016                            return textureId == id;
1017                          }) != mImpl->boundTextures.End();
1018         }
1019       }
1020
1021       if(textureFound)
1022       {
1023         if(instruction.mFrameBuffer)
1024         {
1025           // For off-screen buffer
1026
1027           // Wait until all rendering calls for the currently context are executed
1028           mImpl->graphicsController.GetGlContextHelperAbstraction().WaitClient();
1029
1030           // Clear the dependency list
1031           mImpl->textureDependencyList.Clear();
1032         }
1033         else
1034         {
1035           // Worker thread lambda function
1036           auto& glContextHelperAbstraction = mImpl->graphicsController.GetGlContextHelperAbstraction();
1037           auto  workerFunction             = [&glContextHelperAbstraction](int workerThread) {
1038             // Switch to the shared context in the worker thread
1039             glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1040
1041             // Wait until all rendering calls for the shared context are executed
1042             glContextHelperAbstraction.WaitClient();
1043
1044             // Must clear the context in the worker thread
1045             // Otherwise the shared context cannot be switched to from the render thread
1046             glContextHelperAbstraction.MakeContextNull();
1047           };
1048
1049           auto future = mImpl->threadPool->SubmitTask(0u, workerFunction);
1050           if(future)
1051           {
1052             mImpl->threadPool->Wait();
1053
1054             // Clear the dependency list
1055             mImpl->textureDependencyList.Clear();
1056           }
1057         }
1058       }
1059     }
1060
1061     if(instruction.mRenderTracker && instruction.mFrameBuffer)
1062     {
1063       // This will create a sync object every frame this render tracker
1064       // is alive (though it should be now be created only for
1065       // render-once render tasks)
1066       instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController.GetGlSyncAbstraction());
1067       instruction.mRenderTracker = nullptr; // Only create once.
1068     }
1069
1070     if(renderToFbo)
1071     {
1072       mImpl->currentContext->Flush();
1073     }
1074   }
1075
1076   GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
1077   mImpl->currentContext->InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1078 }
1079
1080 void RenderManager::PostRender(bool uploadOnly)
1081 {
1082   if(!uploadOnly)
1083   {
1084     if(mImpl->currentContext->IsSurfacelessContextSupported())
1085     {
1086       mImpl->graphicsController.GetGlContextHelperAbstraction().MakeSurfacelessContextCurrent();
1087     }
1088
1089     GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
1090     mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1091   }
1092
1093   //Notify RenderGeometries that rendering has finished
1094   for(auto&& iter : mImpl->geometryContainer)
1095   {
1096     iter->OnRenderFinished();
1097   }
1098
1099   mImpl->UpdateTrackers();
1100
1101   uint32_t count = 0u;
1102   for(uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i)
1103   {
1104     count += mImpl->sceneContainer[i]->GetRenderInstructions().Count(mImpl->renderBufferIndex);
1105   }
1106
1107   const bool haveInstructions = count > 0u;
1108
1109   // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1110   mImpl->lastFrameWasRendered = haveInstructions;
1111
1112   /**
1113    * The rendering has finished; swap to the next buffer.
1114    * Ideally the update has just finished using this buffer; otherwise the render thread
1115    * should block until the update has finished.
1116    */
1117   mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1118
1119   DALI_PRINT_RENDER_END();
1120 }
1121
1122 } // namespace SceneGraph
1123
1124 } // namespace Internal
1125
1126 } // namespace Dali