1b871a6f3bf3e8b50b37fb814d595621445ab37d
[platform/core/uifw/dali-core.git] / dali / internal / render / common / render-algorithms.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-algorithms.h>
20
21 // INTERNAL INCLUDES
22 #include <dali/internal/render/common/render-debug.h>
23 #include <dali/internal/render/common/render-instruction.h>
24 #include <dali/internal/render/common/render-list.h>
25 #include <dali/internal/render/gl-resources/context.h>
26 #include <dali/internal/render/renderers/render-renderer.h>
27 #include <dali/internal/update/nodes/scene-graph-layer.h>
28
29 using Dali::Internal::SceneGraph::RenderInstruction;
30 using Dali::Internal::SceneGraph::RenderItem;
31 using Dali::Internal::SceneGraph::RenderList;
32 using Dali::Internal::SceneGraph::RenderListContainer;
33
34 namespace Dali
35 {
36 namespace Internal
37 {
38 namespace Render
39 {
40 namespace
41 {
42 // Table for fast look-up of Dali::DepthFunction enum to a GL depth function.
43 // Note: These MUST be in the same order as Dali::DepthFunction enum.
44 const int DaliDepthToGLDepthTable[] = {GL_NEVER, GL_ALWAYS, GL_LESS, GL_GREATER, GL_EQUAL, GL_NOTEQUAL, GL_LEQUAL, GL_GEQUAL};
45
46 // Table for fast look-up of Dali::StencilFunction enum to a GL stencil function.
47 // Note: These MUST be in the same order as Dali::StencilFunction enum.
48 const int DaliStencilFunctionToGL[] = {GL_NEVER, GL_LESS, GL_EQUAL, GL_LEQUAL, GL_GREATER, GL_NOTEQUAL, GL_GEQUAL, GL_ALWAYS};
49
50 // Table for fast look-up of Dali::StencilOperation enum to a GL stencil operation.
51 // Note: These MUST be in the same order as Dali::StencilOperation enum.
52 const int DaliStencilOperationToGL[] = {GL_ZERO, GL_KEEP, GL_REPLACE, GL_INCR, GL_DECR, GL_INVERT, GL_INCR_WRAP, GL_DECR_WRAP};
53
54 inline Graphics::Viewport ViewportFromClippingBox(ClippingBox clippingBox, int orientation)
55 {
56   Graphics::Viewport viewport{static_cast<float>(clippingBox.x), static_cast<float>(clippingBox.y), static_cast<float>(clippingBox.width), static_cast<float>(clippingBox.height), 0.0f, 0.0f};
57
58   if(orientation == 90 || orientation == 270)
59   {
60     viewport.width  = static_cast<float>(clippingBox.height);
61     viewport.height = static_cast<float>(clippingBox.width);
62   }
63   return viewport;
64 }
65
66 inline Graphics::Rect2D RecalculateRect(Graphics::Rect2D rect, int orientation, Graphics::Viewport viewport)
67 {
68   Graphics::Rect2D newRect;
69
70   // scissor's value should be set based on the default system coordinates.
71   // when the surface is rotated, the input valus already were set with the rotated angle.
72   // So, re-calculation is needed.
73   if(orientation == 90)
74   {
75     newRect.x      = viewport.height - (rect.y + rect.height);
76     newRect.y      = rect.x;
77     newRect.width  = rect.height;
78     newRect.height = rect.width;
79   }
80   else if(orientation == 180)
81   {
82     newRect.x      = viewport.width - (rect.x + rect.width);
83     newRect.y      = viewport.height - (rect.y + rect.height);
84     newRect.width  = rect.width;
85     newRect.height = rect.height;
86   }
87   else if(orientation == 270)
88   {
89     newRect.x      = rect.y;
90     newRect.y      = viewport.width - (rect.x + rect.width);
91     newRect.width  = rect.height;
92     newRect.height = rect.width;
93   }
94   else
95   {
96     newRect.x      = rect.x;
97     newRect.y      = rect.y;
98     newRect.width  = rect.width;
99     newRect.height = rect.height;
100   }
101   return newRect;
102 }
103
104 inline Graphics::Rect2D Rect2DFromClippingBox(ClippingBox clippingBox, int orientation, Graphics::Viewport viewport)
105 {
106   Graphics::Rect2D rect2D{clippingBox.x, clippingBox.y, static_cast<uint32_t>(abs(clippingBox.width)), static_cast<uint32_t>(abs(clippingBox.height))};
107   return RecalculateRect(rect2D, orientation, viewport);
108 }
109
110 inline Graphics::Rect2D Rect2DFromRect(Dali::Rect<int> rect, int orientation, Graphics::Viewport viewport)
111 {
112   Graphics::Rect2D rect2D{rect.x, rect.y, static_cast<uint32_t>(abs(rect.width)), static_cast<uint32_t>(abs(rect.height))};
113   return RecalculateRect(rect2D, orientation, viewport);
114 }
115
116 /**
117  * @brief Find the intersection of two AABB rectangles.
118  * This is a logical AND operation. IE. The intersection is the area overlapped by both rectangles.
119  * @param[in]     aabbA                  Rectangle A
120  * @param[in]     aabbB                  Rectangle B
121  * @return                               The intersection of rectangle A & B (result is a rectangle)
122  */
123 inline ClippingBox IntersectAABB(const ClippingBox& aabbA, const ClippingBox& aabbB)
124 {
125   ClippingBox intersectionBox;
126
127   // First calculate the largest starting positions in X and Y.
128   intersectionBox.x = std::max(aabbA.x, aabbB.x);
129   intersectionBox.y = std::max(aabbA.y, aabbB.y);
130
131   // Now calculate the smallest ending positions, and take the largest starting
132   // positions from the result, to get the width and height respectively.
133   // If the two boxes do not intersect at all, then we need a 0 width and height clipping area.
134   // We use max here to clamp both width and height to >= 0 for this use-case.
135   intersectionBox.width  = std::max(std::min(aabbA.x + aabbA.width, aabbB.x + aabbB.width) - intersectionBox.x, 0);
136   intersectionBox.height = std::max(std::min(aabbA.y + aabbA.height, aabbB.y + aabbB.height) - intersectionBox.y, 0);
137
138   return intersectionBox;
139 }
140
141 /**
142  * @brief Set up the stencil and color buffer for automatic clipping (StencilMode::AUTO).
143  * @param[in]     item                     The current RenderItem about to be rendered
144  * @param[in]     context                  The context
145  * @param[in/out] lastClippingDepth        The stencil depth of the last renderer drawn.
146  * @param[in/out] lastClippingId           The clipping ID of the last renderer drawn.
147  */
148 inline void SetupStencilClipping(const RenderItem& item, Context& context, uint32_t& lastClippingDepth, uint32_t& lastClippingId)
149 {
150   const Dali::Internal::SceneGraph::Node* node       = item.mNode;
151   const uint32_t                          clippingId = node->GetClippingId();
152   // If there is no clipping Id, then either we haven't reached a clipping Node yet, or there aren't any.
153   // Either way we can skip clipping setup for this renderer.
154   if(clippingId == 0u)
155   {
156     // Exit immediately if there are no clipping actions to perform (EG. we have not yet hit a clipping node).
157     context.EnableStencilBuffer(false);
158     return;
159   }
160
161   context.EnableStencilBuffer(true);
162
163   const uint32_t clippingDepth = node->GetClippingDepth();
164
165   // Pre-calculate a mask which has all bits set up to and including the current clipping depth.
166   // EG. If depth is 3, the mask would be "111" in binary.
167   const uint32_t currentDepthMask = (1u << clippingDepth) - 1u;
168
169   // Are we are writing to the stencil buffer?
170   if(item.mNode->GetClippingMode() == Dali::ClippingMode::CLIP_CHILDREN)
171   {
172     // We are writing to the stencil buffer.
173     // If clipping Id is 1, this is the first clipping renderer within this render-list.
174     if(clippingId == 1u)
175     {
176       // We are enabling the stencil-buffer for the first time within this render list.
177       // Clear the buffer at this point.
178       context.StencilMask(0xff);
179       context.Clear(GL_STENCIL_BUFFER_BIT, Context::CHECK_CACHED_VALUES);
180     }
181     else if((clippingDepth < lastClippingDepth) ||
182             ((clippingDepth == lastClippingDepth) && (clippingId > lastClippingId)))
183     {
184       // The above if() statement tests if we need to clear some (not all) stencil bit-planes.
185       // We need to do this if either of the following are true:
186       //   1) We traverse up the scene-graph to a previous stencil depth
187       //   2) We are at the same stencil depth but the clipping Id has increased.
188       //
189       // This calculation takes the new depth to move to, and creates an inverse-mask of that number of consecutive bits.
190       // This has the effect of clearing everything except the bit-planes up to (and including) our current depth.
191       const uint32_t stencilClearMask = (currentDepthMask >> 1u) ^ 0xff;
192
193       context.StencilMask(stencilClearMask);
194       context.Clear(GL_STENCIL_BUFFER_BIT, Context::CHECK_CACHED_VALUES);
195     }
196
197     // We keep track of the last clipping Id and depth so we can determine when we are
198     // moving back up the scene graph and require some of the stencil bit-planes to be deleted.
199     lastClippingDepth = clippingDepth;
200     lastClippingId    = clippingId;
201
202     // We only ever write to bit-planes up to the current depth as we may need
203     // to erase individual bit-planes and revert to a previous clipping area.
204     // Our reference value for testing (in StencilFunc) is written to to the buffer, but we actually
205     // want to test a different value. IE. All the bit-planes up to but not including the current depth.
206     // So we use the Mask parameter of StencilFunc to mask off the top bit-plane when testing.
207     // Here we create our test mask to innore the top bit of the reference test value.
208     // As the mask is made up of contiguous "1" values, we can do this quickly with a bit-shift.
209     const uint32_t testMask = currentDepthMask >> 1u;
210
211     context.StencilFunc(GL_EQUAL, currentDepthMask, testMask); // Test against existing stencil bit-planes. All must match up to (but not including) this depth.
212     context.StencilMask(currentDepthMask);                     // Write to the new stencil bit-plane (the other previous bit-planes are also written to).
213     context.StencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
214   }
215   else
216   {
217     // We are reading from the stencil buffer. Set up the stencil accordingly
218     // This calculation sets all the bits up to the current depth bit.
219     // This has the effect of testing that the pixel being written to exists in every bit-plane up to the current depth.
220     context.StencilFunc(GL_EQUAL, currentDepthMask, currentDepthMask);
221     context.StencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
222   }
223 }
224
225 /**
226  * @brief Sets up the depth buffer for reading and writing based on the current render item.
227  * The items read and write mode are used if specified.
228  *  - If AUTO is selected for reading, the decision will be based on the Layer Behavior.
229  *  - If AUTO is selected for writing, the decision will be based on the items opacity.
230  * @param[in]     item                The RenderItem to set up the depth buffer for.
231  * @param[in]     context             The context used to execute GL commands.
232  * @param[in]     depthTestEnabled    True if depth testing has been enabled.
233  * @param[in/out] firstDepthBufferUse Initialize to true on the first call, this method will set it to false afterwards.
234  */
235 inline void SetupDepthBuffer(const RenderItem& item, Context& context, bool depthTestEnabled, bool& firstDepthBufferUse)
236 {
237   // Set up whether or not to write to the depth buffer.
238   const DepthWriteMode::Type depthWriteMode = item.mRenderer->GetDepthWriteMode();
239   // Most common mode (AUTO) is tested first.
240   const bool enableDepthWrite = ((depthWriteMode == DepthWriteMode::AUTO) && depthTestEnabled && item.mIsOpaque) ||
241                                 (depthWriteMode == DepthWriteMode::ON);
242
243   // Set up whether or not to read from (test) the depth buffer.
244   const DepthTestMode::Type depthTestMode = item.mRenderer->GetDepthTestMode();
245   // Most common mode (AUTO) is tested first.
246   const bool enableDepthTest = ((depthTestMode == DepthTestMode::AUTO) && depthTestEnabled) ||
247                                (depthTestMode == DepthTestMode::ON);
248
249   // Is the depth buffer in use?
250   if(enableDepthWrite || enableDepthTest)
251   {
252     // The depth buffer must be enabled if either reading or writing.
253     context.EnableDepthBuffer(true);
254
255     // Look-up the GL depth function from the Dali::DepthFunction enum, and set it.
256     context.DepthFunc(DaliDepthToGLDepthTable[item.mRenderer->GetDepthFunction()]);
257
258     // If this is the first use of the depth buffer this RenderTask, perform a clear.
259     // Note: We could do this at the beginning of the RenderTask and rely on the
260     // context cache to ignore the clear if not required, but, we would have to enable
261     // the depth buffer to do so, which could be a redundant enable.
262     if(DALI_UNLIKELY(firstDepthBufferUse))
263     {
264       // This is the first time the depth buffer is being written to or read.
265       firstDepthBufferUse = false;
266
267       // Note: The buffer will only be cleared if written to since a previous clear.
268       context.DepthMask(true);
269       context.Clear(GL_DEPTH_BUFFER_BIT, Context::CHECK_CACHED_VALUES);
270     }
271
272     // Set up the depth mask based on our depth write setting.
273     context.DepthMask(enableDepthWrite);
274   }
275   else
276   {
277     // The depth buffer is not being used by this renderer, so we must disable it to stop it being tested.
278     context.EnableDepthBuffer(false);
279   }
280 }
281
282 } // Unnamed namespace
283
284 /**
285  * @brief This method is responsible for making decisions on when to apply and unapply scissor clipping, and what rectangular dimensions should be used.
286  * A stack of scissor clips at each depth of clipping is maintained, so it can be applied and unapplied.
287  * As the clips are hierarchical, this RenderItems AABB is clipped against the current "active" scissor bounds via an intersection operation.
288  * @param[in]     item                     The current RenderItem about to be rendered
289  * @param[in]     context                  The context
290  * @param[in]     instruction              The render-instruction to process.
291  */
292 inline void RenderAlgorithms::SetupScissorClipping(const RenderItem& item, Context& context, const RenderInstruction& instruction)
293 {
294   // Get the number of child scissors in the stack (do not include layer or root box).
295   size_t         childStackDepth = mScissorStack.size() - 1u;
296   const uint32_t scissorDepth    = item.mNode->GetScissorDepth();
297   const bool     clippingNode    = item.mNode->GetClippingMode() == Dali::ClippingMode::CLIP_TO_BOUNDING_BOX;
298   bool           traversedUpTree = false;
299
300   // If we are using scissor clipping and we are at the same depth (or less), we need to undo previous clips.
301   // We do this by traversing up the scissor clip stack and then apply the appropriate clip for the current render item.
302   // To know this, we use clippingDepth. This value is set on *every* node, but only increased as clipping nodes are hit depth-wise.
303   // So we know if we are at depth 4 and the stackDepth is 5, that we have gone up.
304   // If the depth is the same then we are effectively part of a different sub-tree from the parent, we must also remove the current clip.
305   // Note: Stack depth must always be at least 1, as we will have the layer or stage size as the root value.
306   if((childStackDepth > 0u) && (scissorDepth < childStackDepth))
307   {
308     while(scissorDepth < childStackDepth)
309     {
310       mScissorStack.pop_back();
311       --childStackDepth;
312     }
313
314     // We traversed up the tree, we need to apply a new scissor rectangle (unless we are at the root).
315     traversedUpTree = true;
316   }
317   if(clippingNode && childStackDepth > 0u && childStackDepth == scissorDepth) // case of sibling clip area
318   {
319     mScissorStack.pop_back();
320     --childStackDepth;
321   }
322
323   // If we are on a clipping node, or we have traveled up the tree and gone back past a clipping node, may need to apply a new scissor clip.
324   if(clippingNode || traversedUpTree)
325   {
326     // First, check if we are a clipping node.
327     if(clippingNode)
328     {
329       // This is a clipping node. We generate the AABB for this node and intersect it with the previous intersection further up the tree.
330
331       // Get the AABB bounding box for the current render item.
332       const ClippingBox scissorBox(item.CalculateViewportSpaceAABB(item.mSize, mViewportRectangle.width, mViewportRectangle.height));
333
334       // Get the AABB for the parent item that we must intersect with.
335       const ClippingBox& parentBox(mScissorStack.back());
336
337       // We must reduce the clipping area based on the parents area to allow nested clips. This is a set intersection function.
338       // We add the new scissor box to the stack so we can return to it if needed.
339       mScissorStack.emplace_back(IntersectAABB(parentBox, scissorBox));
340     }
341
342     // The scissor test is enabled if we have any children on the stack, OR, if there are none but it is a user specified layer scissor box.
343     // IE. It is not enabled if we are at the top of the stack and the layer does not have a specified clipping box.
344     const bool scissorEnabled = (mScissorStack.size() > 0u) || mHasLayerScissor;
345
346     // Enable the scissor test based on the above calculation
347     if(scissorEnabled)
348     {
349       mGraphicsCommandBuffer->SetScissorTestEnable( scissorEnabled );
350     }
351
352     // If scissor is enabled, we use the calculated screen-space coordinates (now in the stack).
353     if(scissorEnabled)
354     {
355       ClippingBox useScissorBox(mScissorStack.back());
356
357       if(instruction.mFrameBuffer && instruction.GetCamera()->IsYAxisInverted())
358       {
359         useScissorBox.y = (instruction.mFrameBuffer->GetHeight() - useScissorBox.height) - useScissorBox.y;
360       }
361      Graphics::Rect2D scissorBox = {
362         useScissorBox.x, useScissorBox.y,
363        uint32_t(useScissorBox.width), uint32_t(useScissorBox.height)
364       };
365      mGraphicsCommandBuffer->SetScissor( scissorBox );
366     }
367   }
368 }
369
370 inline void RenderAlgorithms::SetupClipping(const RenderItem&                   item,
371                                             Context&                            context,
372                                             bool&                               usedStencilBuffer,
373                                             uint32_t&                           lastClippingDepth,
374                                             uint32_t&                           lastClippingId,
375                                             Integration::StencilBufferAvailable stencilBufferAvailable,
376                                             const RenderInstruction&            instruction)
377 {
378   RenderMode::Type renderMode = RenderMode::AUTO;
379   const Renderer*  renderer   = item.mRenderer;
380   if(renderer)
381   {
382     renderMode = renderer->GetRenderMode();
383   }
384
385   // Setup the stencil using either the automatic clipping feature, or, the manual per-renderer stencil API.
386   // Note: This switch is in order of most likely value first.
387   switch(renderMode)
388   {
389     case RenderMode::AUTO:
390     {
391       // Turn the color buffer on as we always want to render this renderer, regardless of clipping hierarchy.
392       context.ColorMask(true);
393
394       // The automatic clipping feature will manage the scissor and stencil functions, only if stencil buffer is available for the latter.
395       // As both scissor and stencil clips can be nested, we may be simultaneously traversing up the scissor tree, requiring a scissor to be un-done. Whilst simultaneously adding a new stencil clip.
396       // We process both based on our current and old clipping depths for each mode.
397       // Both methods with return rapidly if there is nothing to be done for that type of clipping.
398       SetupScissorClipping(item, context, instruction);
399
400       if(stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
401       {
402         SetupStencilClipping(item, context, lastClippingDepth, lastClippingId);
403       }
404       break;
405     }
406
407     case RenderMode::NONE:
408     case RenderMode::COLOR:
409     {
410       // No clipping is performed for these modes.
411       // Note: We do not turn off scissor clipping as it may be used for the whole layer.
412       // The stencil buffer will not be used at all, but we only need to disable it if it's available.
413       if(stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
414       {
415         context.EnableStencilBuffer(false);
416       }
417
418       // Setup the color buffer based on the RenderMode.
419       context.ColorMask(renderMode == RenderMode::COLOR);
420       break;
421     }
422
423     case RenderMode::STENCIL:
424     case RenderMode::COLOR_STENCIL:
425     {
426       if(stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
427       {
428         // We are using the low-level Renderer Stencil API.
429         // The stencil buffer must be enabled for every renderer with stencil mode on, as renderers in between can disable it.
430         // Note: As the command state is cached, it is only sent when needed.
431         context.EnableStencilBuffer(true);
432
433         // Setup the color buffer based on the RenderMode.
434         context.ColorMask(renderMode == RenderMode::COLOR_STENCIL);
435
436         // If this is the first use of the stencil buffer within this RenderList, clear it (this avoids unnecessary clears).
437         if(!usedStencilBuffer)
438         {
439           context.Clear(GL_STENCIL_BUFFER_BIT, Context::CHECK_CACHED_VALUES);
440           usedStencilBuffer = true;
441         }
442
443         // Setup the stencil buffer based on the renderers properties.
444         context.StencilFunc(DaliStencilFunctionToGL[renderer->GetStencilFunction()],
445                             renderer->GetStencilFunctionReference(),
446                             renderer->GetStencilFunctionMask());
447         context.StencilOp(DaliStencilOperationToGL[renderer->GetStencilOperationOnFail()],
448                           DaliStencilOperationToGL[renderer->GetStencilOperationOnZFail()],
449                           DaliStencilOperationToGL[renderer->GetStencilOperationOnZPass()]);
450         context.StencilMask(renderer->GetStencilMask());
451       }
452       break;
453     }
454   }
455 }
456
457 inline void RenderAlgorithms::ProcessRenderList(const RenderList&                   renderList,
458                                                 Context&                            context,
459                                                 BufferIndex                         bufferIndex,
460                                                 const Matrix&                       viewMatrix,
461                                                 const Matrix&                       projectionMatrix,
462                                                 Integration::DepthBufferAvailable   depthBufferAvailable,
463                                                 Integration::StencilBufferAvailable stencilBufferAvailable,
464                                                 Vector<Graphics::Texture*>&         boundTextures,
465                                                 const RenderInstruction&            instruction,
466                                                 const Rect<int32_t>&                viewport,
467                                                 const Rect<int>&                    rootClippingRect,
468                                                 int                                 orientation)
469 {
470   DALI_PRINT_RENDER_LIST(renderList);
471
472   // Note: The depth buffer is enabled or disabled on a per-renderer basis.
473   // Here we pre-calculate the value to use if these modes are set to AUTO.
474   const bool        autoDepthTestMode((depthBufferAvailable == Integration::DepthBufferAvailable::TRUE) &&
475                                !(renderList.GetSourceLayer()->IsDepthTestDisabled()) &&
476                                renderList.HasColorRenderItems());
477   const std::size_t count = renderList.Count();
478   uint32_t          lastClippingDepth(0u);
479   uint32_t          lastClippingId(0u);
480   bool              usedStencilBuffer(false);
481   bool              firstDepthBufferUse(true);
482
483   mViewportRectangle = viewport;
484   mGraphicsCommandBuffer->SetViewport(ViewportFromClippingBox(mViewportRectangle, orientation));
485   mHasLayerScissor = false;
486
487   // Setup Scissor testing (for both viewport and per-node scissor)
488   mScissorStack.clear();
489
490   // Add root clipping rect (set manually for Render function by partial update for example)
491   // on the bottom of the stack
492   if(!rootClippingRect.IsEmpty())
493   {
494     Graphics::Viewport graphicsViewport = ViewportFromClippingBox(mViewportRectangle, 0);
495     mGraphicsCommandBuffer->SetScissorTestEnable(true);
496     mGraphicsCommandBuffer->SetScissor(Rect2DFromRect(rootClippingRect, orientation, graphicsViewport));
497     mScissorStack.push_back(rootClippingRect);
498   }
499   // We are not performing a layer clip and no clipping rect set. Add the viewport as the root scissor rectangle.
500   else if(!renderList.IsClipping())
501   {
502     mGraphicsCommandBuffer->SetScissorTestEnable(false);
503     mScissorStack.push_back(mViewportRectangle);
504   }
505
506   if(renderList.IsClipping())
507   {
508     Graphics::Viewport graphicsViewport = ViewportFromClippingBox(mViewportRectangle, 0);
509     mGraphicsCommandBuffer->SetScissorTestEnable(true);
510     const ClippingBox& layerScissorBox = renderList.GetClippingBox();
511     mGraphicsCommandBuffer->SetScissor(Rect2DFromClippingBox(layerScissorBox, orientation, graphicsViewport));
512     mScissorStack.push_back(layerScissorBox);
513     mHasLayerScissor = true;
514   }
515
516   mGraphicsRenderItemCommandBuffers.clear();
517   // Loop through all RenderList in the RenderList, set up any prerequisites to render them, then perform the render.
518   for(uint32_t index = 0u; index < count; ++index)
519   {
520     const RenderItem& item = renderList.GetItem(index);
521
522     // Discard renderers outside the root clipping rect
523     bool skip = true;
524     if(!rootClippingRect.IsEmpty())
525     {
526       auto rect = item.CalculateViewportSpaceAABB(item.mUpdateSize, mViewportRectangle.width, mViewportRectangle.height);
527
528       if(rect.Intersect(rootClippingRect))
529       {
530         skip = false;
531       }
532     }
533     else
534     {
535       skip = false;
536     }
537
538     DALI_PRINT_RENDER_ITEM(item);
539
540     // Set up clipping based on both the Renderer and Actor APIs.
541     // The Renderer API will be used if specified. If AUTO, the Actors automatic clipping feature will be used.
542     SetupClipping(item, context, usedStencilBuffer, lastClippingDepth, lastClippingId, stencilBufferAvailable, instruction);
543
544     if(DALI_LIKELY(item.mRenderer))
545     {
546       // Set up the depth buffer based on per-renderer flags if depth buffer is available
547       // If the per renderer flags are set to "ON" or "OFF", they will always override any Layer depth mode or
548       // draw-mode state, such as Overlays.
549       // If the flags are set to "AUTO", the behavior then depends on the type of renderer. Overlay Renderers will always
550       // disable depth testing and writing. Color Renderers will enable them if the Layer does.
551       if(depthBufferAvailable == Integration::DepthBufferAvailable::TRUE)
552       {
553         SetupDepthBuffer(item, context, autoDepthTestMode, firstDepthBufferUse);
554       }
555
556       // Depending on whether the renderer has draw commands attached or not the rendering process will
557       // iterate through all the render queues. If there are no draw commands attached, only one
558       // iteration must be done and the default behaviour of the renderer will be executed.
559       // The queues allow to iterate over the same renderer multiple times changing the state of the renderer.
560       // It is similar to the multi-pass rendering.
561       if(!skip)
562       {
563         auto const MAX_QUEUE = item.mRenderer->GetDrawCommands().empty() ? 1 : DevelRenderer::RENDER_QUEUE_MAX;
564         for(auto queue = 0u; queue < MAX_QUEUE; ++queue)
565         {
566           // Render the item. If rendered, add its command buffer into the list
567           if( item.mRenderer->Render(context, bufferIndex, *item.mNode, item.mModelMatrix, item.mModelViewMatrix, viewMatrix, projectionMatrix, item.mSize, !item.mIsOpaque, boundTextures, instruction, queue) )
568           {
569             mGraphicsRenderItemCommandBuffers.emplace_back( item.mRenderer->GetGraphicsCommandBuffer() );
570           }
571         }
572       }
573     }
574   }
575
576   // Execute command buffers
577   if(!mGraphicsRenderItemCommandBuffers.empty())
578   {
579     mGraphicsCommandBuffer->ExecuteCommandBuffers( std::move(mGraphicsRenderItemCommandBuffers) );
580   }
581 }
582
583 RenderAlgorithms::RenderAlgorithms(Graphics::Controller& graphicsController)
584 : mGraphicsController(graphicsController),
585   mViewportRectangle(),
586   mHasLayerScissor(false)
587 {
588 }
589
590 void RenderAlgorithms::ResetCommandBuffer()
591 {
592   // Reset main command buffer
593   if(!mGraphicsCommandBuffer)
594   {
595     mGraphicsCommandBuffer = mGraphicsController.CreateCommandBuffer(
596       Graphics::CommandBufferCreateInfo()
597         .SetLevel(Graphics::CommandBufferLevel::SECONDARY),
598       nullptr);
599   }
600   else
601   {
602     mGraphicsCommandBuffer->Reset();
603   }
604
605   // Reset list of secondary buffers to submit
606   mGraphicsRenderItemCommandBuffers.clear();
607 }
608
609 void RenderAlgorithms::SubmitCommandBuffer()
610 {
611   // Submit main command buffer
612   Graphics::SubmitInfo submitInfo;
613   submitInfo.cmdBuffer.push_back(  mGraphicsCommandBuffer.get() );
614   submitInfo.flags = 0 | Graphics::SubmitFlagBits::FLUSH;
615   mGraphicsController.SubmitCommandBuffers( submitInfo );
616 }
617
618 void RenderAlgorithms::ProcessRenderInstruction(const RenderInstruction&            instruction,
619                                                 Context&                            context,
620                                                 BufferIndex                         bufferIndex,
621                                                 Integration::DepthBufferAvailable   depthBufferAvailable,
622                                                 Integration::StencilBufferAvailable stencilBufferAvailable,
623                                                 Vector<Graphics::Texture*>&         boundTextures,
624                                                 const Rect<int32_t>&                viewport,
625                                                 const Rect<int>&                    rootClippingRect,
626                                                 int                                 orientation)
627 {
628   DALI_PRINT_RENDER_INSTRUCTION(instruction, bufferIndex);
629
630   const Matrix* viewMatrix       = instruction.GetViewMatrix(bufferIndex);
631   const Matrix* projectionMatrix = instruction.GetProjectionMatrix(bufferIndex);
632
633   DALI_ASSERT_DEBUG(viewMatrix);
634   DALI_ASSERT_DEBUG(projectionMatrix);
635
636   if(viewMatrix && projectionMatrix)
637   {
638     const RenderListContainer::SizeType count = instruction.RenderListCount();
639
640     // Iterate through each render list in order. If a pair of render lists
641     // are marked as interleaved, then process them together.
642     for(RenderListContainer::SizeType index = 0; index < count; ++index)
643     {
644       const RenderList* renderList = instruction.GetRenderList(index);
645
646       if(renderList && !renderList->IsEmpty())
647       {
648         ProcessRenderList(*renderList,
649                           context,
650                           bufferIndex,
651                           *viewMatrix,
652                           *projectionMatrix,
653                           depthBufferAvailable,
654                           stencilBufferAvailable,
655                           boundTextures,
656                           instruction, //added for reflection effect
657                           viewport,
658                           rootClippingRect,
659                           orientation);
660       }
661     }
662   }
663 }
664
665 } // namespace Render
666
667 } // namespace Internal
668
669 } // namespace Dali