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