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/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>
40 #if defined(DEBUG_ENABLED)
41 Debug::Filter* gRenderListLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_LISTS");
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
63 bool PartialCompareItems( const RenderInstructionProcessor::SortAttributes& lhs,
64 const RenderInstructionProcessor::SortAttributes& rhs )
66 if( lhs.shader == rhs.shader )
68 if( lhs.textureSet == rhs.textureSet )
70 return lhs.geometry < rhs.geometry;
72 return lhs.textureSet < rhs.textureSet;
74 return lhs.shader < rhs.shader;
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
84 bool CompareItems( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
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 )
90 return PartialCompareItems(lhs, rhs);
92 return lhs.renderItem->mDepthIndex < rhs.renderItem->mDepthIndex;
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
102 bool CompareItemsWithClipping( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
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 )
107 return CompareItems( lhs, rhs );
110 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
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
120 bool CompareItems3D( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
122 bool lhsIsOpaque = lhs.renderItem->mIsOpaque;
123 if( lhsIsOpaque == rhs.renderItem->mIsOpaque )
127 // If both RenderItems are opaque, sort using shader, then material then geometry.
128 return PartialCompareItems( lhs, rhs );
132 // If both RenderItems are transparent, sort using Z, then shader, then material, then geometry.
133 if( Equals( lhs.zValue, rhs.zValue ) )
135 return PartialCompareItems( lhs, rhs );
137 return lhs.zValue > rhs.zValue;
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
152 bool CompareItems3DWithClipping( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
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 )
157 return CompareItems3D( lhs, rhs );
160 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
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
173 inline void AddRendererToRenderList( BufferIndex updateBufferIndex,
174 RenderList& renderList,
175 Renderable& renderable,
176 const Matrix& viewMatrix,
177 SceneGraph::Camera& camera,
182 const Node* node = renderable.mNode;
184 if( cull && !renderable.mRenderer->GetShader().HintEnabled( Dali::Shader::Hint::MODIFIES_GEOMETRY ) )
186 const Vector4& boundingSphere = node->GetBoundingSphere();
187 inside = ( boundingSphere.w > Math::MACHINE_EPSILON_1000 ) &&
188 ( camera.CheckSphereInFrustum( updateBufferIndex, Vector3( boundingSphere ), boundingSphere.w ) );
193 Renderer::Opacity opacity = renderable.mRenderer->GetOpacity( updateBufferIndex, *renderable.mNode );
194 if( opacity != Renderer::TRANSPARENT )
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();
206 item.mDepthIndex += renderable.mNode->GetDepthIndex();
209 // Save ModelView matrix onto the item.
210 node->GetWorldMatrixAndSize( item.mModelMatrix, item.mSize );
212 Matrix::Multiply( item.mModelViewMatrix, item.mModelMatrix, viewMatrix );
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
228 inline void AddRenderersToRenderList( BufferIndex updateBufferIndex,
229 RenderList& renderList,
230 RenderableContainer& renderers,
231 const Matrix& viewMatrix,
232 SceneGraph::Camera& camera,
236 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "AddRenderersToRenderList()\n");
238 unsigned int rendererCount( renderers.Size() );
239 for( unsigned int i(0); i < rendererCount; ++i )
241 AddRendererToRenderList( updateBufferIndex,
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
259 inline bool TryReuseCachedRenderers( Layer& layer,
260 RenderList& renderList,
261 RenderableContainer& renderables )
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 ) )
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 )
276 const Render::Renderer& renderer = renderables[index].mRenderer->GetRenderer();
277 checkSumNew += size_t( &renderer );
278 checkSumOld += size_t( &renderList.GetRenderer( index ) );
280 if( checkSumNew == checkSumOld )
282 // tell list to reuse its existing items
283 renderList.ReuseCachedItems();
290 inline bool SetupRenderList( RenderableContainer& renderables,
292 RenderInstruction& instruction,
293 bool tryReuseRenderList,
294 RenderList** renderList )
296 *renderList = &( instruction.GetNextFreeRenderList( renderables.Size() ) );
297 ( *renderList )->SetClipping( layer.IsClipping(), layer.GetClippingBox() );
298 ( *renderList )->SetSourceLayer( &layer );
300 // Try to reuse cached RenderItems from last time around.
301 return ( tryReuseRenderList && TryReuseCachedRenderers( layer, **renderList, renderables ) );
304 } // Anonymous namespace.
307 RenderInstructionProcessor::RenderInstructionProcessor()
310 // Set up a container of comparators for fast run-time selection.
311 mSortComparitors.Reserve( 4u );
313 mSortComparitors.PushBack( CompareItems );
314 mSortComparitors.PushBack( CompareItemsWithClipping );
315 mSortComparitors.PushBack( CompareItems3D );
316 mSortComparitors.PushBack( CompareItems3DWithClipping );
319 RenderInstructionProcessor::~RenderInstructionProcessor()
323 inline void RenderInstructionProcessor::SortRenderItems( BufferIndex bufferIndex, RenderList& renderList, Layer& layer, bool respectClippingOrder )
325 const size_t renderableCount = renderList.Count();
326 // Reserve space if needed.
327 const unsigned int oldcapacity = mSortingHelper.size();
328 if( oldcapacity < renderableCount )
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() );
338 // Clear extra elements from helper, does not decrease capability.
339 mSortingHelper.resize( renderableCount );
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() )
346 for( size_t index = 0; index < renderableCount; ++index )
348 RenderItem& item = renderList.GetItem( index );
350 item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
353 mSortingHelper[ index ].textureSet = item.mTextureSet;
355 // The default sorting function should get inlined here.
356 mSortingHelper[ index ].zValue = Internal::Layer::ZValue( item.mModelViewMatrix.GetTranslation3() ) - item.mDepthIndex;
358 // Keep the renderitem pointer in the helper so we can quickly reorder items after sort.
359 mSortingHelper[ index ].renderItem = &item;
364 const Dali::Layer::SortFunctionType sortFunction = layer.GetSortFunction();
365 for( size_t index = 0; index < renderableCount; ++index )
367 RenderItem& item = renderList.GetItem( index );
369 item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
372 mSortingHelper[ index ].textureSet = item.mTextureSet;
375 mSortingHelper[ index ].zValue = (*sortFunction)( item.mModelViewMatrix.GetTranslation3() ) - item.mDepthIndex;
377 // Keep the RenderItem pointer in the helper so we can quickly reorder items after sort.
378 mSortingHelper[ index ].renderItem = &item;
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 );
389 std::stable_sort( mSortingHelper.begin(), mSortingHelper.end(), mSortComparitors[ comparitorIndex ] );
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 )
396 *renderListIter = mSortingHelper[ index ].renderItem;
397 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, " sortedList[%d] = %p\n", index, mSortingHelper[ index ].renderItem->mRenderer);
401 void RenderInstructionProcessor::Prepare( BufferIndex updateBufferIndex,
402 SortedLayerPointers& sortedLayers,
403 RenderTask& renderTask,
405 bool hasClippingNodes,
406 RenderInstructionContainer& instructions )
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();
414 const Matrix& viewMatrix = renderTask.GetViewMatrix( updateBufferIndex );
415 SceneGraph::Camera& camera = renderTask.GetCamera();
417 const SortedLayersIter endIter = sortedLayers.end();
418 for( SortedLayersIter iter = sortedLayers.begin(); iter != endIter; ++iter )
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;
425 if( !layer.colorRenderables.Empty() )
427 RenderableContainer& renderables = layer.colorRenderables;
429 if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
431 renderList->SetHasColorRenderItems( true );
432 AddRenderersToRenderList( updateBufferIndex,
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 );
445 if( !layer.overlayRenderables.Empty() )
447 RenderableContainer& renderables = layer.overlayRenderables;
449 if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
451 renderList->SetHasColorRenderItems( false );
452 AddRenderersToRenderList( updateBufferIndex,
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 );
466 // Inform the render instruction that all renderers have been added and this frame is complete.
467 instruction.UpdateCompleted();