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