2 * Copyright (c) 2016 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <dali/internal/update/manager/render-instruction-processor.h>
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>
39 #if defined(DEBUG_ENABLED)
40 Debug::Filter* gRenderListLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_LISTS");
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
62 bool PartialCompareItems( const RenderInstructionProcessor::SortAttributes& lhs,
63 const RenderInstructionProcessor::SortAttributes& rhs )
65 if( lhs.shader == rhs.shader )
67 if( lhs.textureSet == rhs.textureSet )
69 return lhs.geometry < rhs.geometry;
71 return lhs.textureSet < rhs.textureSet;
73 return lhs.shader < rhs.shader;
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
83 bool CompareItems( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
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 )
89 return PartialCompareItems(lhs, rhs);
91 return lhs.renderItem->mDepthIndex < rhs.renderItem->mDepthIndex;
95 * Function which sorts render items by clipping hierarchy, then depth index and instance
96 * 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
101 bool CompareItemsWithClipping( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
103 // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
104 if( lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier )
106 return CompareItems( lhs, rhs );
109 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
113 * Function which sorts the render items by Z function, then
114 * by instance ptrs of shader / geometry / material.
115 * @param[in] lhs Left hand side item
116 * @param[in] rhs Right hand side item
117 * @return True if left item is greater than right
119 bool CompareItems3D( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
121 bool lhsIsOpaque = lhs.renderItem->mIsOpaque;
122 if( lhsIsOpaque == rhs.renderItem->mIsOpaque )
126 // If both RenderItems are opaque, sort using shader, then material then geometry.
127 return PartialCompareItems( lhs, rhs );
131 // If both RenderItems are transparent, sort using Z, then shader, then material, then geometry.
132 if( Equals( lhs.zValue, rhs.zValue ) )
134 return PartialCompareItems( lhs, rhs );
136 return lhs.zValue > rhs.zValue;
146 * Function which sorts render items by clipping hierarchy, then Z function and instance ptrs of shader / geometry / material.
147 * @param[in] lhs Left hand side item
148 * @param[in] rhs Right hand side item
149 * @return True if left item is greater than right
151 bool CompareItems3DWithClipping( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
153 // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
154 if( lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier )
156 return CompareItems3D( lhs, rhs );
159 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
163 * Add a renderer to the list
164 * @param updateBufferIndex to read the model matrix from
165 * @param renderList to add the item to
166 * @param renderable Node-Renderer pair
167 * @param viewMatrix used to calculate modelview matrix for the item
168 * @param camera The camera used to render
169 * @param isLayer3d Whether we are processing a 3D layer or not
170 * @param cull Whether frustum culling is enabled or not
172 inline void AddRendererToRenderList( BufferIndex updateBufferIndex,
173 RenderList& renderList,
174 Renderable& renderable,
175 const Matrix& viewMatrix,
176 SceneGraph::Camera& camera,
181 const Node* node = renderable.mNode;
183 if( cull && !renderable.mRenderer->GetShader().HintEnabled( Dali::Shader::Hint::MODIFIES_GEOMETRY ) )
185 const Vector4& boundingSphere = node->GetBoundingSphere();
186 inside = ( boundingSphere.w > Math::MACHINE_EPSILON_1000 ) &&
187 ( camera.CheckSphereInFrustum( updateBufferIndex, Vector3( boundingSphere ), boundingSphere.w ) );
192 Renderer::Opacity opacity = renderable.mRenderer->GetOpacity( updateBufferIndex, *renderable.mNode );
193 if( opacity != Renderer::TRANSPARENT )
195 // Get the next free RenderItem.
196 RenderItem& item = renderList.GetNextFreeItem();
197 item.mRenderer = &renderable.mRenderer->GetRenderer();
198 item.mNode = renderable.mNode;
199 item.mTextureSet = renderable.mRenderer->GetTextures();
200 item.mIsOpaque = ( opacity == Renderer::OPAQUE );
201 item.mDepthIndex = renderable.mRenderer->GetDepthIndex();
205 item.mDepthIndex += renderable.mNode->GetDepthIndex();
208 // Save ModelView matrix onto the item.
209 node->GetWorldMatrixAndSize( item.mModelMatrix, item.mSize );
211 Matrix::Multiply( item.mModelViewMatrix, item.mModelMatrix, viewMatrix );
217 * Add all renderers to the list
218 * @param updateBufferIndex to read the model matrix from
219 * @param renderList to add the items to
220 * @param renderers to render
221 * NodeRendererContainer Node-Renderer pairs
222 * @param viewMatrix used to calculate modelview matrix for the items
223 * @param camera The camera used to render
224 * @param isLayer3d Whether we are processing a 3D layer or not
225 * @param cull Whether frustum culling is enabled or not
227 inline void AddRenderersToRenderList( BufferIndex updateBufferIndex,
228 RenderList& renderList,
229 RenderableContainer& renderers,
230 const Matrix& viewMatrix,
231 SceneGraph::Camera& camera,
235 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "AddRenderersToRenderList()\n");
237 unsigned int rendererCount( renderers.Size() );
238 for( unsigned int i(0); i < rendererCount; ++i )
240 AddRendererToRenderList( updateBufferIndex,
251 * Try to reuse cached RenderItems from the RenderList
252 * This avoids recalculating the model view matrices in case this part of the scene was static
253 * An example case is a toolbar layer that rarely changes or a popup on top of the rest of the stage
254 * @param layer that is being processed
255 * @param renderList that is cached from frame N-1
256 * @param renderables list of renderables
258 inline bool TryReuseCachedRenderers( Layer& layer,
259 RenderList& renderList,
260 RenderableContainer& renderables )
262 bool retValue = false;
263 size_t renderableCount = renderables.Size();
264 // Check that the cached list originates from this layer and that the counts match
265 if( ( renderList.GetSourceLayer() == &layer )&&
266 ( renderList.GetCachedItemCount() == renderableCount ) )
268 // Check that all the same renderers are there. This gives us additional security in avoiding rendering the wrong things.
269 // Render list is sorted so at this stage renderers may be in different order.
270 // Therefore we check a combined sum of all renderer addresses.
271 size_t checkSumNew = 0;
272 size_t checkSumOld = 0;
273 for( size_t index = 0; index < renderableCount; ++index )
275 const Render::Renderer& renderer = renderables[index].mRenderer->GetRenderer();
276 checkSumNew += size_t( &renderer );
277 checkSumOld += size_t( &renderList.GetRenderer( index ) );
279 if( checkSumNew == checkSumOld )
281 // tell list to reuse its existing items
282 renderList.ReuseCachedItems();
289 inline bool SetupRenderList( RenderableContainer& renderables,
291 RenderInstruction& instruction,
292 bool tryReuseRenderList,
293 RenderList** renderList )
295 *renderList = &( instruction.GetNextFreeRenderList( renderables.Size() ) );
296 ( *renderList )->SetClipping( layer.IsClipping(), layer.GetClippingBox() );
297 ( *renderList )->SetSourceLayer( &layer );
299 // Try to reuse cached RenderItems from last time around.
300 return ( tryReuseRenderList && TryReuseCachedRenderers( layer, **renderList, renderables ) );
303 } // Anonymous namespace.
306 RenderInstructionProcessor::RenderInstructionProcessor()
309 // Set up a container of comparators for fast run-time selection.
310 mSortComparitors.Reserve( 4u );
312 mSortComparitors.PushBack( CompareItems );
313 mSortComparitors.PushBack( CompareItemsWithClipping );
314 mSortComparitors.PushBack( CompareItems3D );
315 mSortComparitors.PushBack( CompareItems3DWithClipping );
318 RenderInstructionProcessor::~RenderInstructionProcessor()
322 inline void RenderInstructionProcessor::SortRenderItems( BufferIndex bufferIndex, RenderList& renderList, Layer& layer, bool respectClippingOrder )
324 const size_t renderableCount = renderList.Count();
325 // Reserve space if needed.
326 const unsigned int oldcapacity = mSortingHelper.size();
327 if( oldcapacity < renderableCount )
329 mSortingHelper.reserve( renderableCount );
330 // Add real objects (reserve does not construct objects).
331 mSortingHelper.insert( mSortingHelper.begin() + oldcapacity,
332 (renderableCount - oldcapacity),
333 RenderInstructionProcessor::SortAttributes() );
337 // Clear extra elements from helper, does not decrease capability.
338 mSortingHelper.resize( renderableCount );
341 // Calculate the sorting value, once per item by calling the layers sort function.
342 // Using an if and two for-loops rather than if inside for as its better for branch prediction.
343 if( layer.UsesDefaultSortFunction() )
345 for( size_t index = 0; index < renderableCount; ++index )
347 RenderItem& item = renderList.GetItem( index );
349 item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
352 mSortingHelper[ index ].textureSet = item.mTextureSet;
354 // The default sorting function should get inlined here.
355 mSortingHelper[ index ].zValue = Internal::Layer::ZValue( item.mModelViewMatrix.GetTranslation3() ) - item.mDepthIndex;
357 // Keep the renderitem pointer in the helper so we can quickly reorder items after sort.
358 mSortingHelper[ index ].renderItem = &item;
363 const Dali::Layer::SortFunctionType sortFunction = layer.GetSortFunction();
364 for( size_t index = 0; index < renderableCount; ++index )
366 RenderItem& item = renderList.GetItem( index );
368 item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
371 mSortingHelper[ index ].textureSet = item.mTextureSet;
374 mSortingHelper[ index ].zValue = (*sortFunction)( item.mModelViewMatrix.GetTranslation3() ) - item.mDepthIndex;
376 // Keep the RenderItem pointer in the helper so we can quickly reorder items after sort.
377 mSortingHelper[ index ].renderItem = &item;
381 // Here we detemine which comparitor (of the 4) to use.
382 // The comparitors work like a bitmask.
383 // 1 << 0 is added to select a clipping comparitor.
384 // 1 << 1 is added for 3D comparitors.
385 const unsigned int comparitorIndex = ( respectClippingOrder ? ( 1u << 0u ) : 0u ) |
386 ( layer.GetBehavior() == Dali::Layer::LAYER_3D ? ( 1u << 1u ) : 0u );
388 std::stable_sort( mSortingHelper.begin(), mSortingHelper.end(), mSortComparitors[ comparitorIndex ] );
390 // Reorder / re-populate the RenderItems in the RenderList to correct order based on the sortinghelper.
391 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "Sorted Transparent List:\n");
392 RenderItemContainer::Iterator renderListIter = renderList.GetContainer().Begin();
393 for( unsigned int index = 0; index < renderableCount; ++index, ++renderListIter )
395 *renderListIter = mSortingHelper[ index ].renderItem;
396 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, " sortedList[%d] = %p\n", index, mSortingHelper[ index ].renderItem->mRenderer);
400 void RenderInstructionProcessor::Prepare( BufferIndex updateBufferIndex,
401 SortedLayerPointers& sortedLayers,
402 RenderTask& renderTask,
404 bool hasClippingNodes,
405 RenderInstructionContainer& instructions )
407 // Retrieve the RenderInstruction buffer from the RenderInstructionContainer
408 // then populate with instructions.
409 RenderInstruction& instruction = instructions.GetNextInstruction( updateBufferIndex );
410 renderTask.PrepareRenderInstruction( instruction, updateBufferIndex );
411 bool viewMatrixHasNotChanged = !renderTask.ViewMatrixUpdated();
413 const Matrix& viewMatrix = renderTask.GetViewMatrix( updateBufferIndex );
414 SceneGraph::Camera& camera = renderTask.GetCamera();
416 const SortedLayersIter endIter = sortedLayers.end();
417 for( SortedLayersIter iter = sortedLayers.begin(); iter != endIter; ++iter )
419 Layer& layer = **iter;
420 const bool tryReuseRenderList( viewMatrixHasNotChanged && layer.CanReuseRenderers( &renderTask.GetCamera() ) );
421 const bool isLayer3D = layer.GetBehavior() == Dali::Layer::LAYER_3D;
422 RenderList* renderList = NULL;
424 if( !layer.colorRenderables.Empty() )
426 RenderableContainer& renderables = layer.colorRenderables;
428 if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
430 renderList->SetHasColorRenderItems( true );
431 AddRenderersToRenderList( updateBufferIndex,
439 // We only use the clipping version of the sort comparitor if any clipping nodes exist within the RenderList.
440 SortRenderItems( updateBufferIndex, *renderList, layer, hasClippingNodes );
444 if( !layer.overlayRenderables.Empty() )
446 RenderableContainer& renderables = layer.overlayRenderables;
448 if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
450 renderList->SetHasColorRenderItems( false );
451 AddRenderersToRenderList( updateBufferIndex,
459 // Clipping hierarchy is irrelevant when sorting overlay items, so we specify using the non-clipping version of the sort comparitor.
460 SortRenderItems( updateBufferIndex, *renderList, layer, false );
465 // Inform the render instruction that all renderers have been added and this frame is complete.
466 instruction.UpdateCompleted();