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