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