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