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