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