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