Perform AABB test in the viewport space for renderers when not processing a 3D layer
[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
28 #include <dali/internal/event/common/scene-impl.h>
29
30 #include <dali/internal/update/common/scene-graph-scene.h>
31 #include <dali/internal/update/render-tasks/scene-graph-camera.h>
32
33 #include <dali/internal/render/common/render-algorithms.h>
34 #include <dali/internal/render/common/render-debug.h>
35 #include <dali/internal/render/common/render-instruction.h>
36 #include <dali/internal/render/common/render-tracker.h>
37 #include <dali/internal/render/queue/render-queue.h>
38 #include <dali/internal/render/renderers/pipeline-cache.h>
39 #include <dali/internal/render/renderers/render-frame-buffer.h>
40 #include <dali/internal/render/renderers/render-texture.h>
41 #include <dali/internal/render/renderers/shader-cache.h>
42 #include <dali/internal/render/renderers/uniform-buffer-manager.h>
43 #include <dali/internal/render/renderers/uniform-buffer-view-pool.h>
44 #include <dali/internal/render/shaders/program-controller.h>
45
46 #include <memory>
47
48 namespace Dali
49 {
50 namespace Internal
51 {
52 namespace SceneGraph
53 {
54 #if defined(DEBUG_ENABLED)
55 namespace
56 {
57 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER");
58 } // unnamed namespace
59 #endif
60
61 namespace
62 {
63 inline Graphics::Rect2D RecalculateScissorArea(Graphics::Rect2D scissorArea, int orientation, Rect<int32_t> viewportRect)
64 {
65   Graphics::Rect2D newScissorArea;
66
67   if(orientation == 90)
68   {
69     newScissorArea.x      = viewportRect.height - (scissorArea.y + scissorArea.height);
70     newScissorArea.y      = scissorArea.x;
71     newScissorArea.width  = scissorArea.height;
72     newScissorArea.height = scissorArea.width;
73   }
74   else if(orientation == 180)
75   {
76     newScissorArea.x      = viewportRect.width - (scissorArea.x + scissorArea.width);
77     newScissorArea.y      = viewportRect.height - (scissorArea.y + scissorArea.height);
78     newScissorArea.width  = scissorArea.width;
79     newScissorArea.height = scissorArea.height;
80   }
81   else if(orientation == 270)
82   {
83     newScissorArea.x      = scissorArea.y;
84     newScissorArea.y      = viewportRect.width - (scissorArea.x + scissorArea.width);
85     newScissorArea.width  = scissorArea.height;
86     newScissorArea.height = scissorArea.width;
87   }
88   else
89   {
90     newScissorArea.x      = scissorArea.x;
91     newScissorArea.y      = scissorArea.y;
92     newScissorArea.width  = scissorArea.width;
93     newScissorArea.height = scissorArea.height;
94   }
95   return newScissorArea;
96 }
97 } // namespace
98 /**
99  * Structure to contain internal data
100  */
101 struct RenderManager::Impl
102 {
103   Impl(Graphics::Controller&               graphicsController,
104        Integration::DepthBufferAvailable   depthBufferAvailableParam,
105        Integration::StencilBufferAvailable stencilBufferAvailableParam,
106        Integration::PartialUpdateAvailable partialUpdateAvailableParam)
107   : graphicsController(graphicsController),
108     renderQueue(),
109     renderAlgorithms(graphicsController),
110     frameCount(0u),
111     renderBufferIndex(SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX),
112     rendererContainer(),
113     samplerContainer(),
114     textureContainer(),
115     frameBufferContainer(),
116     lastFrameWasRendered(false),
117     programController(graphicsController),
118     shaderCache(graphicsController),
119     depthBufferAvailable(depthBufferAvailableParam),
120     stencilBufferAvailable(stencilBufferAvailableParam),
121     partialUpdateAvailable(partialUpdateAvailableParam)
122   {
123     // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
124     threadPool = std::make_unique<Dali::ThreadPool>();
125     threadPool->Initialize(1u);
126
127     uniformBufferManager = std::make_unique<Render::UniformBufferManager>(&graphicsController);
128     pipelineCache        = std::make_unique<Render::PipelineCache>(graphicsController);
129   }
130
131   ~Impl()
132   {
133     threadPool.reset(nullptr); // reset now to maintain correct destruction order
134   }
135
136   void AddRenderTracker(Render::RenderTracker* renderTracker)
137   {
138     DALI_ASSERT_DEBUG(renderTracker != nullptr);
139     mRenderTrackers.PushBack(renderTracker);
140   }
141
142   void RemoveRenderTracker(Render::RenderTracker* renderTracker)
143   {
144     mRenderTrackers.EraseObject(renderTracker);
145   }
146
147   void UpdateTrackers()
148   {
149     for(auto&& iter : mRenderTrackers)
150     {
151       iter->PollSyncObject();
152     }
153   }
154
155   // the order is important for destruction,
156   Graphics::Controller& graphicsController;
157   RenderQueue           renderQueue; ///< A message queue for receiving messages from the update-thread.
158
159   std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
160
161   Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
162
163   uint32_t    frameCount;        ///< The current frame count
164   BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
165
166   OwnerContainer<Render::Renderer*>     rendererContainer;     ///< List of owned renderers
167   OwnerContainer<Render::Sampler*>      samplerContainer;      ///< List of owned samplers
168   OwnerContainer<Render::Texture*>      textureContainer;      ///< List of owned textures
169   OwnerContainer<Render::FrameBuffer*>  frameBufferContainer;  ///< List of owned framebuffers
170   OwnerContainer<Render::VertexBuffer*> vertexBufferContainer; ///< List of owned vertex buffers
171   OwnerContainer<Render::Geometry*>     geometryContainer;     ///< List of owned Geometries
172
173   bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
174
175   OwnerContainer<Render::RenderTracker*> mRenderTrackers; ///< List of render trackers
176
177   ProgramController   programController; ///< Owner of the programs
178   Render::ShaderCache shaderCache;       ///< The cache for the graphics shaders
179
180   std::unique_ptr<Render::UniformBufferManager> uniformBufferManager; ///< The uniform buffer manager
181   std::unique_ptr<Render::PipelineCache>        pipelineCache;
182
183   Integration::DepthBufferAvailable   depthBufferAvailable;   ///< Whether the depth buffer is available
184   Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
185   Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
186
187   std::unique_ptr<Dali::ThreadPool> threadPool;            ///< The thread pool
188   Vector<Graphics::Texture*>        boundTextures;         ///< The textures bound for rendering
189   Vector<Graphics::Texture*>        textureDependencyList; ///< The dependency list of bound textures
190 };
191
192 RenderManager* RenderManager::New(Graphics::Controller&               graphicsController,
193                                   Integration::DepthBufferAvailable   depthBufferAvailable,
194                                   Integration::StencilBufferAvailable stencilBufferAvailable,
195                                   Integration::PartialUpdateAvailable partialUpdateAvailable)
196 {
197   auto* manager  = new RenderManager;
198   manager->mImpl = new Impl(graphicsController,
199                             depthBufferAvailable,
200                             stencilBufferAvailable,
201                             partialUpdateAvailable);
202   return manager;
203 }
204
205 RenderManager::RenderManager()
206 : mImpl(nullptr)
207 {
208 }
209
210 RenderManager::~RenderManager()
211 {
212   delete mImpl;
213 }
214
215 RenderQueue& RenderManager::GetRenderQueue()
216 {
217   return mImpl->renderQueue;
218 }
219
220 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
221 {
222 }
223
224 void RenderManager::AddRenderer(OwnerPointer<Render::Renderer>& renderer)
225 {
226   // Initialize the renderer as we are now in render thread
227   renderer->Initialize(mImpl->graphicsController, mImpl->programController, mImpl->shaderCache, *(mImpl->uniformBufferManager.get()), *(mImpl->pipelineCache.get()));
228
229   mImpl->rendererContainer.PushBack(renderer.Release());
230 }
231
232 void RenderManager::RemoveRenderer(Render::Renderer* renderer)
233 {
234   mImpl->rendererContainer.EraseObject(renderer);
235 }
236
237 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
238 {
239   sampler->Initialize(mImpl->graphicsController);
240   mImpl->samplerContainer.PushBack(sampler.Release());
241 }
242
243 void RenderManager::RemoveSampler(Render::Sampler* sampler)
244 {
245   mImpl->samplerContainer.EraseObject(sampler);
246 }
247
248 void RenderManager::AddTexture(OwnerPointer<Render::Texture>& texture)
249 {
250   texture->Initialize(mImpl->graphicsController);
251   mImpl->textureContainer.PushBack(texture.Release());
252 }
253
254 void RenderManager::RemoveTexture(Render::Texture* texture)
255 {
256   DALI_ASSERT_DEBUG(NULL != texture);
257
258   // Find the texture, use reference to pointer so we can do the erase safely
259   for(auto&& iter : mImpl->textureContainer)
260   {
261     if(iter == texture)
262     {
263       texture->Destroy();
264       mImpl->textureContainer.Erase(&iter); // Texture found; now destroy it
265       return;
266     }
267   }
268 }
269
270 void RenderManager::UploadTexture(Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params)
271 {
272   texture->Upload(pixelData, params);
273 }
274
275 void RenderManager::GenerateMipmaps(Render::Texture* texture)
276 {
277   texture->GenerateMipmaps();
278 }
279
280 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
281 {
282   sampler->SetFilterMode(static_cast<Dali::FilterMode::Type>(minFilterMode),
283                          static_cast<Dali::FilterMode::Type>(magFilterMode));
284 }
285
286 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
287 {
288   sampler->SetWrapMode(static_cast<Dali::WrapMode::Type>(rWrapMode),
289                        static_cast<Dali::WrapMode::Type>(sWrapMode),
290                        static_cast<Dali::WrapMode::Type>(tWrapMode));
291 }
292
293 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
294 {
295   Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
296   mImpl->frameBufferContainer.PushBack(frameBufferPtr);
297   frameBufferPtr->Initialize(mImpl->graphicsController);
298 }
299
300 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
301 {
302   DALI_ASSERT_DEBUG(nullptr != frameBuffer);
303
304   // Find the sampler, use reference so we can safely do the erase
305   for(auto&& iter : mImpl->frameBufferContainer)
306   {
307     if(iter == frameBuffer)
308     {
309       frameBuffer->Destroy();
310       mImpl->frameBufferContainer.Erase(&iter); // frameBuffer found; now destroy it
311
312       break;
313     }
314   }
315 }
316
317 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
318 {
319   scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
320   mImpl->sceneContainer.push_back(scene);
321 }
322
323 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
324 {
325   auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
326   if(iter != mImpl->sceneContainer.end())
327   {
328     mImpl->sceneContainer.erase(iter);
329   }
330 }
331
332 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
333 {
334   scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
335 }
336
337 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
338 {
339   frameBuffer->AttachColorTexture(texture, mipmapLevel, layer);
340 }
341
342 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
343 {
344   frameBuffer->AttachDepthTexture(texture, mipmapLevel);
345 }
346
347 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
348 {
349   frameBuffer->AttachDepthStencilTexture(texture, mipmapLevel);
350 }
351
352 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
353 {
354   mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
355 }
356
357 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
358 {
359   mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
360 }
361
362 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
363 {
364   vertexBuffer->SetFormat(format.Release());
365 }
366
367 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
368 {
369   vertexBuffer->SetData(data.Release(), size);
370 }
371
372 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Dali::Vector<uint16_t>& indices)
373 {
374   geometry->SetIndexBuffer(indices);
375 }
376
377 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
378 {
379   mImpl->geometryContainer.PushBack(geometry.Release());
380 }
381
382 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
383 {
384   auto it = std::find_if(mImpl->geometryContainer.begin(), mImpl->geometryContainer.end(), [geometry](auto& item) {
385     return geometry == item;
386   });
387
388   if(it != mImpl->geometryContainer.end())
389   {
390     mImpl->geometryContainer.Erase(it);
391   }
392 }
393
394 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
395 {
396   DALI_ASSERT_DEBUG(nullptr != geometry);
397
398   // Find the geometry
399   for(auto&& iter : mImpl->geometryContainer)
400   {
401     if(iter == geometry)
402     {
403       iter->AddVertexBuffer(vertexBuffer);
404       break;
405     }
406   }
407 }
408
409 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
410 {
411   DALI_ASSERT_DEBUG(nullptr != geometry);
412
413   // Find the geometry
414   for(auto&& iter : mImpl->geometryContainer)
415   {
416     if(iter == geometry)
417     {
418       iter->RemoveVertexBuffer(vertexBuffer);
419       break;
420     }
421   }
422 }
423
424 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
425 {
426   geometry->SetType(Render::Geometry::Type(geometryType));
427 }
428
429 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
430 {
431   mImpl->AddRenderTracker(renderTracker);
432 }
433
434 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
435 {
436   mImpl->RemoveRenderTracker(renderTracker);
437 }
438
439 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear, bool uploadOnly)
440 {
441   DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
442
443   // Rollback
444   mImpl->uniformBufferManager->GetUniformBufferViewPool(mImpl->renderBufferIndex)->Rollback();
445
446   // Increment the frame count at the beginning of each frame
447   ++mImpl->frameCount;
448
449   // Process messages queued during previous update
450   mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
451
452   uint32_t count = 0u;
453   for(auto& i : mImpl->sceneContainer)
454   {
455     count += i->GetRenderInstructions().Count(mImpl->renderBufferIndex);
456   }
457
458   const bool haveInstructions = count > 0u;
459
460   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");
461
462   // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
463   if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
464   {
465     DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
466
467     // Upload the geometries
468     for(auto&& geom : mImpl->geometryContainer)
469     {
470       geom->Upload(mImpl->graphicsController);
471     }
472   }
473 }
474
475 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
476 {
477   if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
478   {
479     return;
480   }
481
482   Internal::Scene&   sceneInternal = GetImplementation(scene);
483   SceneGraph::Scene* sceneObject   = sceneInternal.GetSceneObject();
484
485   if(sceneObject->IsRenderingSkipped())
486   {
487     // We don't need to calculate dirty rects
488     return;
489   }
490
491   class DamagedRectsCleaner
492   {
493   public:
494     explicit DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects)
495     : mDamagedRects(damagedRects),
496       mCleanOnReturn(true)
497     {
498     }
499
500     void SetCleanOnReturn(bool cleanOnReturn)
501     {
502       mCleanOnReturn = cleanOnReturn;
503     }
504
505     ~DamagedRectsCleaner()
506     {
507       if(mCleanOnReturn)
508       {
509         mDamagedRects.clear();
510       }
511     }
512
513   private:
514     std::vector<Rect<int>>& mDamagedRects;
515     bool                    mCleanOnReturn;
516   };
517
518   Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
519
520   // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
521   DamagedRectsCleaner damagedRectCleaner(damagedRects);
522
523   // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
524   // so you don't need to sort: std::stable_sort(itemsDirtyRects.begin(), itemsDirtyRects.end());
525   std::vector<DirtyRect>& itemsDirtyRects = sceneInternal.GetItemsDirtyRects();
526   for(DirtyRect& dirtyRect : itemsDirtyRects)
527   {
528     dirtyRect.visited = false;
529   }
530
531   uint32_t instructionCount = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
532   for(uint32_t i = 0; i < instructionCount; ++i)
533   {
534     RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
535
536     if(instruction.mFrameBuffer)
537     {
538       return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
539     }
540
541     const Camera* camera = instruction.GetCamera();
542     if(camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
543     {
544       const Node* node = instruction.GetCamera()->GetNode();
545       if(node)
546       {
547         Vector3    position;
548         Vector3    scale;
549         Quaternion orientation;
550         node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
551
552         Vector3 orientationAxis;
553         Radian  orientationAngle;
554         orientation.ToAxisAngle(orientationAxis, orientationAngle);
555
556         if(position.x > Math::MACHINE_EPSILON_10000 ||
557            position.y > Math::MACHINE_EPSILON_10000 ||
558            orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
559            orientationAngle != ANGLE_180 ||
560            scale != Vector3(1.0f, 1.0f, 1.0f))
561         {
562           return;
563         }
564       }
565     }
566     else
567     {
568       return;
569     }
570
571     Rect<int32_t> viewportRect;
572     if(instruction.mIsViewportSet)
573     {
574       const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
575       viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
576       if(viewportRect.IsEmpty() || !viewportRect.IsValid())
577       {
578         return; // just skip funny use cases for now, empty viewport means it is set somewhere else
579       }
580     }
581     else
582     {
583       viewportRect = surfaceRect;
584     }
585
586     const Matrix* viewMatrix       = instruction.GetViewMatrix(mImpl->renderBufferIndex);
587     const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
588     if(viewMatrix && projectionMatrix)
589     {
590       const RenderListContainer::SizeType count = instruction.RenderListCount();
591       for(RenderListContainer::SizeType index = 0u; index < count; ++index)
592       {
593         const RenderList* renderList = instruction.GetRenderList(index);
594         if(renderList && !renderList->IsEmpty())
595         {
596           const std::size_t listCount = renderList->Count();
597           for(uint32_t listIndex = 0u; listIndex < listCount; ++listIndex)
598           {
599             RenderItem& item = renderList->GetItem(listIndex);
600             // If the item does 3D transformation, do early exit and clean the damaged rect array
601             if(item.mUpdateSize == Vector3::ZERO)
602             {
603               return;
604             }
605
606             Rect<int> rect;
607             DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
608             // If the item refers to updated node or renderer.
609             if(item.mIsUpdated ||
610                (item.mNode &&
611                 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
612             {
613               item.mIsUpdated = false;
614               item.mNode->SetUpdatedTree(false);
615
616               rect = RenderItem::CalculateViewportSpaceAABB(item.mModelViewMatrix, item.mUpdateSize, viewportRect.width, viewportRect.height);
617               if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
618               {
619                 const int left   = rect.x;
620                 const int top    = rect.y;
621                 const int right  = rect.x + rect.width;
622                 const int bottom = rect.y + rect.height;
623                 rect.x           = (left / 16) * 16;
624                 rect.y           = (top / 16) * 16;
625                 rect.width       = ((right + 16) / 16) * 16 - rect.x;
626                 rect.height      = ((bottom + 16) / 16) * 16 - rect.y;
627
628                 // Found valid dirty rect.
629                 // 1. Insert it in the sorted array of the dirty rects.
630                 // 2. Mark the related dirty rects as visited so they will not be removed below.
631                 // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
632                 dirtyRect.rect    = rect;
633                 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
634                 dirtyRectPos      = itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
635
636                 int c = 1;
637                 while(++dirtyRectPos != itemsDirtyRects.end())
638                 {
639                   if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
640                   {
641                     break;
642                   }
643
644                   dirtyRectPos->visited = true;
645                   Rect<int>& dirtRect   = dirtyRectPos->rect;
646                   rect.Merge(dirtRect);
647
648                   c++;
649                   if(c > 3) // no more then 3 previous rects
650                   {
651                     itemsDirtyRects.erase(dirtyRectPos);
652                     break;
653                   }
654                 }
655
656                 damagedRects.push_back(rect);
657               }
658             }
659             else
660             {
661               // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
662               // 2. Mark the related dirty rects as visited so they will not be removed below.
663               auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
664               while(dirtyRectPos != itemsDirtyRects.end())
665               {
666                 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
667                 {
668                   break;
669                 }
670
671                 dirtyRectPos->visited = true;
672                 dirtyRectPos++;
673               }
674             }
675           }
676         }
677       }
678     }
679   }
680
681   // Check removed nodes or removed renderers dirty rects
682   auto i = itemsDirtyRects.begin();
683   auto j = itemsDirtyRects.begin();
684   while(i != itemsDirtyRects.end())
685   {
686     if(i->visited)
687     {
688       *j++ = *i;
689     }
690     else
691     {
692       Rect<int>& dirtRect = i->rect;
693       damagedRects.push_back(dirtRect);
694     }
695     i++;
696   }
697
698   itemsDirtyRects.resize(j - itemsDirtyRects.begin());
699   damagedRectCleaner.SetCleanOnReturn(false);
700 }
701
702 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
703 {
704   Rect<int> clippingRect;
705   RenderScene(status, scene, renderToFbo, clippingRect);
706 }
707
708 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
709 {
710   // Reset main algorithms command buffer
711   mImpl->renderAlgorithms.ResetCommandBuffer();
712
713   auto mainCommandBuffer = mImpl->renderAlgorithms.GetMainCommandBuffer();
714
715   Internal::Scene&   sceneInternal = GetImplementation(scene);
716   SceneGraph::Scene* sceneObject   = sceneInternal.GetSceneObject();
717
718   uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
719
720   std::vector<Graphics::RenderTarget*> targetstoPresent;
721
722   for(uint32_t i = 0; i < count; ++i)
723   {
724     RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
725
726     if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
727     {
728       continue; // skip
729     }
730
731     // Mark that we will require a post-render step to be performed (includes swap-buffers).
732     status.SetNeedsPostRender(true);
733
734     Rect<int32_t> viewportRect;
735
736     Rect<int32_t> surfaceRect        = sceneObject->GetSurfaceRect();
737     int32_t       surfaceOrientation = sceneObject->GetSurfaceOrientation();
738
739     // @todo Should these be part of scene?
740     Integration::DepthBufferAvailable   depthBufferAvailable   = mImpl->depthBufferAvailable;
741     Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
742
743     Graphics::RenderTarget*           currentRenderTarget = nullptr;
744     Graphics::RenderPass*             currentRenderPass   = nullptr;
745     std::vector<Graphics::ClearValue> currentClearValues{};
746
747     if(instruction.mFrameBuffer)
748     {
749       // Ensure graphics framebuffer is created, bind attachments and create render passes
750       // Only happens once per framebuffer. If the create fails, e.g. no attachments yet,
751       // then don't render to this framebuffer.
752       if(!instruction.mFrameBuffer->GetGraphicsObject())
753       {
754         const bool created = instruction.mFrameBuffer->CreateGraphicsObjects();
755         if(!created)
756         {
757           continue;
758         }
759       }
760
761       auto& clearValues = instruction.mFrameBuffer->GetGraphicsRenderPassClearValues();
762
763       // Set the clear color for first color attachment
764       if(instruction.mIsClearColorSet && !clearValues.empty())
765       {
766         clearValues[0].color = {
767           instruction.mClearColor.r,
768           instruction.mClearColor.g,
769           instruction.mClearColor.b,
770           instruction.mClearColor.a};
771       }
772
773       currentClearValues = clearValues;
774
775       auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
776
777       // offscreen buffer
778       currentRenderTarget = instruction.mFrameBuffer->GetGraphicsRenderTarget();
779       currentRenderPass   = instruction.mFrameBuffer->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
780     }
781     else // no framebuffer
782     {
783       // surface
784       auto& clearValues = sceneObject->GetGraphicsRenderPassClearValues();
785
786       if(instruction.mIsClearColorSet)
787       {
788         clearValues[0].color = {
789           instruction.mClearColor.r,
790           instruction.mClearColor.g,
791           instruction.mClearColor.b,
792           instruction.mClearColor.a};
793       }
794
795       currentClearValues = clearValues;
796
797       // @todo SceneObject should already have the depth clear / stencil clear in the clearValues array.
798       // if the window has a depth/stencil buffer.
799       if((depthBufferAvailable == Integration::DepthBufferAvailable::TRUE ||
800           stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE) &&
801          (currentClearValues.size() <= 1))
802       {
803         currentClearValues.emplace_back();
804         currentClearValues.back().depthStencil.depth   = 0;
805         currentClearValues.back().depthStencil.stencil = 0;
806       }
807
808       auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
809
810       currentRenderTarget = sceneObject->GetSurfaceRenderTarget();
811       currentRenderPass   = sceneObject->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
812     }
813
814     targetstoPresent.emplace_back(currentRenderTarget);
815
816     // reset the program matrices for all programs once per frame
817     // this ensures we will set view and projection matrix once per program per camera
818     mImpl->programController.ResetProgramMatrices();
819
820     if(instruction.mFrameBuffer)
821     {
822       // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
823       for(unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
824       {
825         mImpl->textureDependencyList.PushBack(instruction.mFrameBuffer->GetTexture(i0));
826       }
827     }
828
829     if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
830     {
831       // Offscreen buffer rendering
832       if(instruction.mIsViewportSet)
833       {
834         // For Viewport the lower-left corner is (0,0)
835         const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
836         viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
837       }
838       else
839       {
840         viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
841       }
842       surfaceOrientation = 0;
843     }
844     else // No Offscreen frame buffer rendering
845     {
846       // Check whether a viewport is specified, otherwise the full surface size is used
847       if(instruction.mIsViewportSet)
848       {
849         // For Viewport the lower-left corner is (0,0)
850         const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
851         viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
852       }
853       else
854       {
855         viewportRect = surfaceRect;
856       }
857     }
858
859     // Set surface orientation
860     // @todo Inform graphics impl by another route.
861     // was: mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
862
863     /*** Clear region of framebuffer or surface before drawing ***/
864     bool clearFullFrameRect = (surfaceRect == viewportRect);
865     if(instruction.mFrameBuffer != nullptr)
866     {
867       Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
868       clearFullFrameRect = (frameRect == viewportRect);
869     }
870
871     if(!clippingRect.IsEmpty())
872     {
873       if(!clippingRect.Intersect(viewportRect))
874       {
875         DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
876         clippingRect = Rect<int>();
877       }
878       clearFullFrameRect = false;
879     }
880
881     Graphics::Rect2D scissorArea{viewportRect.x, viewportRect.y, uint32_t(viewportRect.width), uint32_t(viewportRect.height)};
882     if(instruction.mIsClearColorSet)
883     {
884       if(!clearFullFrameRect)
885       {
886         if(!clippingRect.IsEmpty())
887         {
888           scissorArea = {clippingRect.x, clippingRect.y, uint32_t(clippingRect.width), uint32_t(clippingRect.height)};
889         }
890       }
891     }
892
893     // Scissor's value should be set based on the default system coordinates.
894     // When the surface is rotated, the input values already were set with the rotated angle.
895     // So, re-calculation is needed.
896     scissorArea = RecalculateScissorArea(scissorArea, surfaceOrientation, viewportRect);
897
898     // Begin render pass
899     mainCommandBuffer->BeginRenderPass(
900       currentRenderPass,
901       currentRenderTarget,
902       scissorArea,
903       currentClearValues);
904
905     mainCommandBuffer->SetViewport({float(viewportRect.x),
906                                     float(viewportRect.y),
907                                     float(viewportRect.width),
908                                     float(viewportRect.height)});
909
910     // Clear the list of bound textures
911     mImpl->boundTextures.Clear();
912
913     mImpl->renderAlgorithms.ProcessRenderInstruction(
914       instruction,
915       mImpl->renderBufferIndex,
916       depthBufferAvailable,
917       stencilBufferAvailable,
918       mImpl->boundTextures,
919       viewportRect,
920       clippingRect,
921       surfaceOrientation);
922
923     Graphics::SyncObject* syncObject{nullptr};
924     // If the render instruction has an associated render tracker (owned separately)
925     // and framebuffer, create a one shot sync object, and use it to determine when
926     // the render pass has finished executing on GPU.
927     if(instruction.mRenderTracker && instruction.mFrameBuffer)
928     {
929       syncObject                 = instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController);
930       instruction.mRenderTracker = nullptr;
931     }
932     mainCommandBuffer->EndRenderPass(syncObject);
933   }
934   mImpl->renderAlgorithms.SubmitCommandBuffer();
935
936   std::sort(targetstoPresent.begin(), targetstoPresent.end());
937
938   Graphics::RenderTarget* rt = nullptr;
939   for(auto& target : targetstoPresent)
940   {
941     if(target != rt)
942     {
943       mImpl->graphicsController.PresentRenderTarget(target);
944       rt = target;
945     }
946   }
947 }
948
949 void RenderManager::PostRender(bool uploadOnly)
950 {
951   // Notify RenderGeometries that rendering has finished
952   for(auto&& iter : mImpl->geometryContainer)
953   {
954     iter->OnRenderFinished();
955   }
956
957   mImpl->UpdateTrackers();
958
959   uint32_t count = 0u;
960   for(auto& scene : mImpl->sceneContainer)
961   {
962     count += scene->GetRenderInstructions().Count(mImpl->renderBufferIndex);
963   }
964
965   const bool haveInstructions = count > 0u;
966
967   // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
968   mImpl->lastFrameWasRendered = haveInstructions;
969
970   /**
971    * The rendering has finished; swap to the next buffer.
972    * Ideally the update has just finished using this buffer; otherwise the render thread
973    * should block until the update has finished.
974    */
975   mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
976
977   DALI_PRINT_RENDER_END();
978 }
979
980 } // namespace SceneGraph
981
982 } // namespace Internal
983
984 } // namespace Dali