cd7ccb20bdd62ef468259ab71264006c543bc30f
[platform/core/uifw/dali-core.git] / dali / internal / update / manager / render-instruction-processor.cpp
1 /*
2  * Copyright (c) 2022 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/update/manager/render-instruction-processor.h>
20
21 // INTERNAL INCLUDES
22 #include <dali/integration-api/debug.h>
23 #include <dali/internal/common/matrix-utils.h>
24 #include <dali/internal/event/actors/layer-impl.h> // for the default sorting function
25 #include <dali/internal/render/common/render-instruction-container.h>
26 #include <dali/internal/render/common/render-instruction.h>
27 #include <dali/internal/render/common/render-item.h>
28 #include <dali/internal/render/common/render-tracker.h>
29 #include <dali/internal/render/renderers/render-renderer.h>
30 #include <dali/internal/render/shaders/render-shader.h>
31 #include <dali/internal/update/manager/sorted-layers.h>
32 #include <dali/internal/update/nodes/scene-graph-layer.h>
33 #include <dali/internal/update/render-tasks/scene-graph-render-task.h>
34 #include <dali/internal/update/rendering/scene-graph-texture-set.h>
35 #include <dali/public-api/actors/layer.h>
36
37 namespace
38 {
39 #if defined(DEBUG_ENABLED)
40 Debug::Filter* gRenderListLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_LISTS");
41 #endif
42 } // namespace
43
44 namespace Dali
45 {
46 namespace Internal
47 {
48 namespace SceneGraph
49 {
50 namespace
51 {
52 /**
53  * Function which compares render items by shader/textureSet/geometry
54  * @param[in] lhs Left hand side item
55  * @param[in] rhs Right hand side item
56  * @return True if left item is greater than right
57  */
58 inline bool PartialCompareItems(const RenderInstructionProcessor::SortAttributes& lhs,
59                                 const RenderInstructionProcessor::SortAttributes& rhs)
60 {
61   if(lhs.shader == rhs.shader)
62   {
63     if(lhs.textureSet == rhs.textureSet)
64     {
65       return lhs.geometry < rhs.geometry;
66     }
67     return lhs.textureSet < rhs.textureSet;
68   }
69   return lhs.shader < rhs.shader;
70 }
71
72 /**
73  * Function which sorts render items by depth index then by instance
74  * ptrs of shader/textureSet/geometry.
75  * @param[in] lhs Left hand side item
76  * @param[in] rhs Right hand side item
77  * @return True if left item is greater than right
78  */
79 bool CompareItems(const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs)
80 {
81   // @todo Consider replacing all these sortAttributes with a single long int that
82   // encapsulates the same data (e.g. the middle-order bits of the ptrs).
83   if(lhs.renderItem->mDepthIndex == rhs.renderItem->mDepthIndex)
84   {
85     return PartialCompareItems(lhs, rhs);
86   }
87   return lhs.renderItem->mDepthIndex < rhs.renderItem->mDepthIndex;
88 }
89
90 /**
91  * Function which sorts the render items by Z function, then
92  * by instance ptrs of shader / geometry / material.
93  * @param[in] lhs Left hand side item
94  * @param[in] rhs Right hand side item
95  * @return True if left item is greater than right
96  */
97 bool CompareItems3D(const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs)
98 {
99   const bool lhsIsOpaque = lhs.renderItem->mIsOpaque;
100   if(lhsIsOpaque == rhs.renderItem->mIsOpaque)
101   {
102     if(lhsIsOpaque)
103     {
104       // If both RenderItems are opaque, sort using shader, then material then geometry.
105       return PartialCompareItems(lhs, rhs);
106     }
107     else
108     {
109       // If both RenderItems are transparent, sort using Z, then shader, then material, then geometry.
110       if(Equals(lhs.zValue, rhs.zValue))
111       {
112         return PartialCompareItems(lhs, rhs);
113       }
114       return lhs.zValue > rhs.zValue;
115     }
116   }
117   else
118   {
119     return lhsIsOpaque;
120   }
121 }
122
123 /**
124  * Function which sorts render items by clipping hierarchy, then Z function and instance ptrs of shader / geometry / material.
125  * @param[in] lhs Left hand side item
126  * @param[in] rhs Right hand side item
127  * @return True if left item is greater than right
128  */
129 bool CompareItems3DWithClipping(const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs)
130 {
131   // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
132   if(lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier)
133   {
134     return CompareItems3D(lhs, rhs);
135   }
136
137   return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
138 }
139
140 /**
141  * Set the update area of the node
142  * @param[in] node The node of the renderer
143  * @param[in] isLayer3d Whether we are processing a 3D layer or not
144  * @param[in,out] nodeWorldMatrix The world matrix of the node
145  * @param[in,out] nodeSize The size of the node
146  * @param[in,out] nodeUpdateArea The update area of the node
147  *
148  * @return True if node use it's own UpdateAreaHint, or z transform occured. False if we use nodeUpdateArea equal with Vector4(0, 0, nodeSize.width, nodeSize.height).
149  */
150 inline bool SetNodeUpdateArea(Node* node, bool isLayer3d, Matrix& nodeWorldMatrix, Vector3& nodeSize, Vector4& nodeUpdateArea)
151 {
152   node->GetWorldMatrixAndSize(nodeWorldMatrix, nodeSize);
153
154   if(node->GetUpdateAreaHint() == Vector4::ZERO)
155   {
156     // RenderItem::CalculateViewportSpaceAABB cannot cope with z transform
157     // I don't use item.mModelMatrix.GetTransformComponents() for z transform, would be too slow
158     if(!isLayer3d && nodeWorldMatrix.GetZAxis() == Vector3(0.0f, 0.0f, 1.0f))
159     {
160       nodeUpdateArea = Vector4(0.0f, 0.0f, nodeSize.width, nodeSize.height);
161       return false;
162     }
163     // Keep nodeUpdateArea as Vector4::ZERO, and return true.
164     return true;
165   }
166   else
167   {
168     nodeUpdateArea = node->GetUpdateAreaHint();
169     return true;
170   }
171 }
172
173 /**
174  * Add a renderer to the list
175  * @param updateBufferIndex to read the model matrix from
176  * @param renderList to add the item to
177  * @param renderable Node-Renderer pair
178  * @param viewMatrix used to calculate modelview matrix for the item
179  * @param camera The camera used to render
180  * @param isLayer3d Whether we are processing a 3D layer or not
181  * @param viewportSet Whether the viewport is set or not
182  * @param viewport The viewport
183  * @param cull Whether frustum culling is enabled or not
184  */
185 inline void AddRendererToRenderList(BufferIndex               updateBufferIndex,
186                                     RenderList&               renderList,
187                                     Renderable&               renderable,
188                                     const Matrix&             viewMatrix,
189                                     const SceneGraph::Camera& camera,
190                                     bool                      isLayer3d,
191                                     bool                      viewportSet,
192                                     const Viewport&           viewport,
193                                     bool                      cull)
194 {
195   bool    inside(true);
196   Node*   node = renderable.mNode;
197   Matrix  nodeWorldMatrix(false);
198   Vector3 nodeSize;
199   Vector4 nodeUpdateArea;
200   bool    nodeUpdateAreaSet(false);
201   bool    nodeUpdateAreaUseHint(false);
202   Matrix  nodeModelViewMatrix(false);
203   bool    nodeModelViewMatrixSet(false);
204
205   // Don't cull items which have render callback
206   bool hasRenderCallback = (renderable.mRenderer && renderable.mRenderer->GetRenderCallback());
207
208   if(cull && renderable.mRenderer && (hasRenderCallback || (!renderable.mRenderer->GetShader().HintEnabled(Dali::Shader::Hint::MODIFIES_GEOMETRY) && node->GetClippingMode() == ClippingMode::DISABLED)))
209   {
210     const Vector4& boundingSphere = node->GetBoundingSphere();
211     inside                        = (boundingSphere.w > Math::MACHINE_EPSILON_1000) &&
212              (camera.CheckSphereInFrustum(updateBufferIndex, Vector3(boundingSphere), boundingSphere.w));
213
214     if(inside && !isLayer3d && viewportSet)
215     {
216       nodeUpdateAreaUseHint = SetNodeUpdateArea(node, isLayer3d, nodeWorldMatrix, nodeSize, nodeUpdateArea);
217       nodeUpdateAreaSet     = true;
218
219       const Vector3& scale = node->GetWorldScale(updateBufferIndex);
220       const Vector3& size  = Vector3(nodeUpdateArea.z, nodeUpdateArea.w, 1.0f) * scale;
221
222       if(size.LengthSquared() > Math::MACHINE_EPSILON_1000)
223       {
224         MatrixUtils::Multiply(nodeModelViewMatrix, nodeWorldMatrix, viewMatrix);
225         nodeModelViewMatrixSet = true;
226
227         // Assume actors are at z=0, compute AABB in view space & test rect intersection
228         // against z=0 plane boundaries for frustum. (NOT viewport). This should take into account
229         // magnification due to FOV etc.
230         ClippingBox boundingBox = RenderItem::CalculateTransformSpaceAABB(nodeModelViewMatrix, Vector3(nodeUpdateArea.x, nodeUpdateArea.y, 0.0f), Vector3(nodeUpdateArea.z, nodeUpdateArea.w, 0.0f));
231         ClippingBox clippingBox(camera.mLeftClippingPlane, camera.mBottomClippingPlane, camera.mRightClippingPlane - camera.mLeftClippingPlane, fabsf(camera.mBottomClippingPlane - camera.mTopClippingPlane));
232         inside = clippingBox.Intersects(boundingBox);
233       }
234     }
235     /*
236      * Note, the API Camera::CheckAABBInFrustum() can be used to test if a bounding box is (partially/fully) inside the view frustum.
237      */
238   }
239
240   if(inside)
241   {
242     bool skipRender(false);
243     bool isOpaque = true;
244     if(!hasRenderCallback)
245     {
246       Renderer::OpacityType opacityType = renderable.mRenderer ? renderable.mRenderer->GetOpacityType(updateBufferIndex, *node) : Renderer::OPAQUE;
247
248       // We can skip render when node is not clipping and transparent
249       skipRender = (opacityType == Renderer::TRANSPARENT && node->GetClippingMode() == ClippingMode::DISABLED);
250
251       isOpaque = (opacityType == Renderer::OPAQUE);
252     }
253
254     if(!skipRender)
255     {
256       // Get the next free RenderItem.
257       RenderItem& item = renderList.GetNextFreeItem();
258
259       // Get cached values
260       auto& partialRenderingData = node->GetPartialRenderingData();
261
262       auto& partialRenderingCacheInfo = node->GetPartialRenderingData().GetCurrentCacheInfo();
263
264       partialRenderingCacheInfo.node       = node;
265       partialRenderingCacheInfo.isOpaque   = isOpaque;
266       partialRenderingCacheInfo.renderer   = renderable.mRenderer;
267       partialRenderingCacheInfo.color      = node->GetWorldColor(updateBufferIndex);
268       partialRenderingCacheInfo.depthIndex = node->GetDepthIndex();
269
270       if(DALI_LIKELY(renderable.mRenderer))
271       {
272         partialRenderingCacheInfo.color.a *= renderable.mRenderer->GetOpacity(updateBufferIndex);
273         partialRenderingCacheInfo.textureSet = renderable.mRenderer->GetTextureSet();
274       }
275
276       item.mNode     = node;
277       item.mIsOpaque = isOpaque;
278       item.mColor    = node->GetColor(updateBufferIndex);
279
280       item.mDepthIndex = 0;
281       if(!isLayer3d)
282       {
283         item.mDepthIndex = node->GetDepthIndex();
284       }
285
286       if(DALI_LIKELY(renderable.mRenderer))
287       {
288         item.mRenderer   = &renderable.mRenderer->GetRenderer();
289         item.mTextureSet = renderable.mRenderer->GetTextureSet();
290         item.mDepthIndex += renderable.mRenderer->GetDepthIndex();
291
292         // Get whether collected map is up to date
293         item.mIsUpdated |= renderable.mRenderer->UniformMapUpdated();
294       }
295       else
296       {
297         item.mRenderer = nullptr;
298       }
299
300       item.mIsUpdated |= isLayer3d;
301
302       if(!nodeUpdateAreaSet)
303       {
304         nodeUpdateAreaUseHint = SetNodeUpdateArea(node, isLayer3d, nodeWorldMatrix, nodeSize, nodeUpdateArea);
305       }
306
307       item.mSize        = nodeSize;
308       item.mUpdateArea  = nodeUpdateArea;
309       item.mModelMatrix = nodeWorldMatrix;
310
311       // Apply transform informations if node doesn't have update size hint and use VisualRenderer.
312       if(!nodeUpdateAreaUseHint && renderable.mRenderer && renderable.mRenderer->GetVisualProperties())
313       {
314         Vector3 updateSize = renderable.mRenderer->CalculateVisualTransformedUpdateSize(updateBufferIndex, Vector3(item.mUpdateArea.z, item.mUpdateArea.w, 0.0f));
315         item.mUpdateArea.z = updateSize.x;
316         item.mUpdateArea.w = updateSize.y;
317       }
318
319       if(!nodeModelViewMatrixSet)
320       {
321         MatrixUtils::Multiply(nodeModelViewMatrix, nodeWorldMatrix, viewMatrix);
322       }
323       item.mModelViewMatrix = nodeModelViewMatrix;
324
325       partialRenderingCacheInfo.matrix              = item.mModelViewMatrix;
326       partialRenderingCacheInfo.size                = item.mSize;
327       partialRenderingCacheInfo.updatedPositionSize = item.mUpdateArea;
328
329       item.mIsUpdated = partialRenderingData.IsUpdated() || item.mIsUpdated;
330
331       partialRenderingData.mRendered = true;
332
333       partialRenderingData.SwapBuffers();
334     }
335     else
336     {
337       // Mark as not rendered
338       auto& partialRenderingData     = node->GetPartialRenderingData();
339       partialRenderingData.mRendered = false;
340     }
341
342     node->SetCulled(updateBufferIndex, false);
343   }
344   else
345   {
346     // Mark as not rendered
347     auto& partialRenderingData     = node->GetPartialRenderingData();
348     partialRenderingData.mRendered = false;
349
350     node->SetCulled(updateBufferIndex, true);
351   }
352 }
353
354 /**
355  * Add all renderers to the list
356  * @param updateBufferIndex to read the model matrix from
357  * @param renderList to add the items to
358  * @param renderers to render
359  * NodeRendererContainer Node-Renderer pairs
360  * @param viewMatrix used to calculate modelview matrix for the items
361  * @param camera The camera used to render
362  * @param isLayer3d Whether we are processing a 3D layer or not
363  * @param cull Whether frustum culling is enabled or not
364  */
365 inline void AddRenderersToRenderList(BufferIndex               updateBufferIndex,
366                                      RenderList&               renderList,
367                                      RenderableContainer&      renderers,
368                                      const Matrix&             viewMatrix,
369                                      const SceneGraph::Camera& camera,
370                                      bool                      isLayer3d,
371                                      bool                      viewportSet,
372                                      const Viewport&           viewport,
373                                      bool                      cull)
374 {
375   DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, "AddRenderersToRenderList()\n");
376
377   for(auto&& renderer : renderers)
378   {
379     AddRendererToRenderList(updateBufferIndex,
380                             renderList,
381                             renderer,
382                             viewMatrix,
383                             camera,
384                             isLayer3d,
385                             viewportSet,
386                             viewport,
387                             cull);
388   }
389 }
390
391 /**
392  * Try to reuse cached RenderItems from the RenderList
393  * This avoids recalculating the model view matrices in case this part of the scene was static
394  * An example case is a toolbar layer that rarely changes or a popup on top of the rest of the stage
395  * @param layer that is being processed
396  * @param renderList that is cached from frame N-1
397  * @param renderables list of renderables
398  */
399 inline bool TryReuseCachedRenderers(Layer&               layer,
400                                     RenderList&          renderList,
401                                     RenderableContainer& renderables)
402 {
403   bool     retValue        = false;
404   uint32_t renderableCount = static_cast<uint32_t>(renderables.Size());
405   // Check that the cached list originates from this layer and that the counts match
406   if((renderList.GetSourceLayer() == &layer) &&
407      (renderList.GetCachedItemCount() == renderableCount))
408   {
409     // Check that all the same renderers are there. This gives us additional security in avoiding rendering the wrong things.
410     // Render list is sorted so at this stage renderers may be in different order.
411     // Therefore we check a combined sum of all renderer addresses.
412     size_t checkSumNew = 0;
413     size_t checkSumOld = 0;
414     for(uint32_t index = 0; index < renderableCount; ++index)
415     {
416       if(DALI_LIKELY(renderables[index].mRenderer))
417       {
418         const Render::Renderer& renderer = renderables[index].mRenderer->GetRenderer();
419         checkSumNew += reinterpret_cast<std::size_t>(&renderer);
420       }
421       if(DALI_LIKELY(renderList.GetItem(index).mRenderer))
422       {
423         checkSumOld += reinterpret_cast<std::size_t>(&renderList.GetRenderer(index));
424       }
425     }
426     if(checkSumNew == checkSumOld)
427     {
428       // tell list to reuse its existing items
429       renderList.ReuseCachedItems();
430       retValue = true;
431     }
432   }
433
434   return retValue;
435 }
436
437 inline bool SetupRenderList(RenderableContainer& renderables,
438                             Layer&               layer,
439                             RenderInstruction&   instruction,
440                             bool                 tryReuseRenderList,
441                             RenderList**         renderList)
442 {
443   *renderList = &(instruction.GetNextFreeRenderList(renderables.Size()));
444   (*renderList)->SetClipping(layer.IsClipping(), layer.GetClippingBox());
445   (*renderList)->SetSourceLayer(&layer);
446
447   // Try to reuse cached RenderItems from last time around.
448   return (tryReuseRenderList && TryReuseCachedRenderers(layer, **renderList, renderables));
449 }
450
451 } // Anonymous namespace.
452
453 RenderInstructionProcessor::RenderInstructionProcessor()
454 : mSortingHelper()
455 {
456   // Set up a container of comparators for fast run-time selection.
457   mSortComparitors.Reserve(3u);
458
459   mSortComparitors.PushBack(CompareItems);
460   mSortComparitors.PushBack(CompareItems3D);
461   mSortComparitors.PushBack(CompareItems3DWithClipping);
462 }
463
464 RenderInstructionProcessor::~RenderInstructionProcessor() = default;
465
466 inline void RenderInstructionProcessor::SortRenderItems(BufferIndex bufferIndex, RenderList& renderList, Layer& layer, bool respectClippingOrder, bool isOrthographicCamera)
467 {
468   const uint32_t renderableCount = static_cast<uint32_t>(renderList.Count());
469   // Reserve space if needed.
470   const uint32_t oldcapacity = static_cast<uint32_t>(mSortingHelper.size());
471   if(oldcapacity < renderableCount)
472   {
473     mSortingHelper.reserve(renderableCount);
474     // Add real objects (reserve does not construct objects).
475     mSortingHelper.insert(mSortingHelper.begin() + oldcapacity,
476                           (renderableCount - oldcapacity),
477                           RenderInstructionProcessor::SortAttributes());
478   }
479   else
480   {
481     // Clear extra elements from helper, does not decrease capability.
482     mSortingHelper.resize(renderableCount);
483   }
484
485   // Calculate the sorting value, once per item by calling the layers sort function.
486   // Using an if and two for-loops rather than if inside for as its better for branch prediction.
487
488   // List of zValue calculating functions.
489   const Dali::Layer::SortFunctionType zValueFunctionFromVector3[] = {
490     [](const Vector3& position) { return position.z; },
491     [](const Vector3& position) { return position.LengthSquared(); },
492     layer.GetSortFunction(),
493   };
494
495   // Determine whether we need to use zValue as Euclidean distance or translatoin's z value.
496   // If layer is LAYER_UI or camera is OrthographicProjection mode, we don't need to calculate
497   // renderItem's distance from camera.
498
499   // Here we determine which zValue SortFunctionType (of the 3) to use.
500   //   0 is position z value : Default LAYER_UI or Orthographic camera
501   //   1 is distance square value : Default LAYER_3D and Perspective camera
502   //   2 is user defined function.
503   const int zValueFunctionIndex = layer.UsesDefaultSortFunction() ? ((layer.GetBehavior() == Dali::Layer::LAYER_UI || isOrthographicCamera) ? 0 : 1) : 2;
504
505   for(uint32_t index = 0; index < renderableCount; ++index)
506   {
507     RenderItem& item = renderList.GetItem(index);
508
509     if(DALI_LIKELY(item.mRenderer))
510     {
511       item.mRenderer->SetSortAttributes(mSortingHelper[index]);
512     }
513
514     // texture set
515     mSortingHelper[index].textureSet = item.mTextureSet;
516
517     mSortingHelper[index].zValue = zValueFunctionFromVector3[zValueFunctionIndex](item.mModelViewMatrix.GetTranslation3()) - static_cast<float>(item.mDepthIndex);
518
519     // Keep the renderitem pointer in the helper so we can quickly reorder items after sort.
520     mSortingHelper[index].renderItem = &item;
521   }
522
523   // Here we determine which comparitor (of the 3) to use.
524   //   0 is LAYER_UI
525   //   1 is LAYER_3D
526   //   2 is LAYER_3D + Clipping
527   const unsigned int comparitorIndex = layer.GetBehavior() == Dali::Layer::LAYER_3D ? respectClippingOrder ? 2u : 1u : 0u;
528
529   std::stable_sort(mSortingHelper.begin(), mSortingHelper.end(), mSortComparitors[comparitorIndex]);
530
531   // Reorder / re-populate the RenderItems in the RenderList to correct order based on the sortinghelper.
532   DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, "Sorted Transparent List:\n");
533   RenderItemContainer::Iterator renderListIter = renderList.GetContainer().Begin();
534   for(uint32_t index = 0; index < renderableCount; ++index, ++renderListIter)
535   {
536     *renderListIter = mSortingHelper[index].renderItem;
537     DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, "  sortedList[%d] = %p\n", index, mSortingHelper[index].renderItem->mRenderer);
538   }
539 }
540
541 void RenderInstructionProcessor::Prepare(BufferIndex                 updateBufferIndex,
542                                          SortedLayerPointers&        sortedLayers,
543                                          RenderTask&                 renderTask,
544                                          bool                        cull,
545                                          bool                        hasClippingNodes,
546                                          RenderInstructionContainer& instructions)
547 {
548   // Retrieve the RenderInstruction buffer from the RenderInstructionContainer
549   // then populate with instructions.
550   RenderInstruction& instruction             = renderTask.PrepareRenderInstruction(updateBufferIndex);
551   bool               viewMatrixHasNotChanged = !renderTask.ViewMatrixUpdated();
552   bool               isRenderListAdded       = false;
553   bool               isRootLayerDirty        = false;
554
555   const Matrix&             viewMatrix           = renderTask.GetViewMatrix(updateBufferIndex);
556   const SceneGraph::Camera& camera               = renderTask.GetCamera();
557   const bool                isOrthographicCamera = camera.mProjectionMode == Dali::Camera::ProjectionMode::ORTHOGRAPHIC_PROJECTION;
558
559   Viewport viewport;
560   bool     viewportSet = renderTask.QueryViewport(updateBufferIndex, viewport);
561
562   const SortedLayersIter endIter = sortedLayers.end();
563   for(SortedLayersIter iter = sortedLayers.begin(); iter != endIter; ++iter)
564   {
565     Layer&      layer = **iter;
566     const bool  tryReuseRenderList(viewMatrixHasNotChanged && layer.CanReuseRenderers(&camera));
567     const bool  isLayer3D  = layer.GetBehavior() == Dali::Layer::LAYER_3D;
568     RenderList* renderList = nullptr;
569
570     if(layer.IsRoot() && (layer.GetDirtyFlags() != NodePropertyFlags::NOTHING))
571     {
572       // If root-layer & dirty, i.e. a property has changed or a child has been deleted, then we need to ensure we render once more
573       isRootLayerDirty = true;
574     }
575
576     if(!layer.colorRenderables.Empty())
577     {
578       RenderableContainer& renderables = layer.colorRenderables;
579
580       if(!SetupRenderList(renderables, layer, instruction, tryReuseRenderList, &renderList))
581       {
582         renderList->SetHasColorRenderItems(true);
583         AddRenderersToRenderList(updateBufferIndex,
584                                  *renderList,
585                                  renderables,
586                                  viewMatrix,
587                                  camera,
588                                  isLayer3D,
589                                  viewportSet,
590                                  viewport,
591                                  cull);
592
593         // We only use the clipping version of the sort comparitor if any clipping nodes exist within the RenderList.
594         SortRenderItems(updateBufferIndex, *renderList, layer, hasClippingNodes, isOrthographicCamera);
595       }
596
597       isRenderListAdded = true;
598     }
599
600     if(!layer.overlayRenderables.Empty())
601     {
602       RenderableContainer& renderables = layer.overlayRenderables;
603
604       if(!SetupRenderList(renderables, layer, instruction, tryReuseRenderList, &renderList))
605       {
606         renderList->SetHasColorRenderItems(false);
607         AddRenderersToRenderList(updateBufferIndex,
608                                  *renderList,
609                                  renderables,
610                                  viewMatrix,
611                                  camera,
612                                  isLayer3D,
613                                  viewportSet,
614                                  viewport,
615                                  cull);
616
617         // Clipping hierarchy is irrelevant when sorting overlay items, so we specify using the non-clipping version of the sort comparitor.
618         SortRenderItems(updateBufferIndex, *renderList, layer, false, isOrthographicCamera);
619       }
620
621       isRenderListAdded = true;
622     }
623   }
624
625   // Inform the render instruction that all renderers have been added and this frame is complete.
626   instruction.UpdateCompleted();
627
628   if(isRenderListAdded || instruction.mIsClearColorSet || isRootLayerDirty)
629   {
630     instructions.PushBack(updateBufferIndex, &instruction);
631   }
632 }
633
634 } // namespace SceneGraph
635
636 } // namespace Internal
637
638 } // namespace Dali