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/devel-api/shader-effects/shader-effect.h>
23 #include <dali/public-api/actors/layer.h>
24 #include <dali/integration-api/debug.h>
25 #include <dali/internal/event/actors/layer-impl.h> // for the default sorting function
26 #include <dali/internal/update/manager/sorted-layers.h>
27 #include <dali/internal/update/render-tasks/scene-graph-render-task.h>
28 #include <dali/internal/update/rendering/scene-graph-texture-set.h>
29 #include <dali/internal/update/resources/resource-manager-declarations.h>
30 #include <dali/internal/render/common/render-item.h>
31 #include <dali/internal/render/common/render-tracker.h>
32 #include <dali/internal/render/common/render-instruction.h>
33 #include <dali/internal/render/common/render-instruction-container.h>
34 #include <dali/internal/render/shaders/scene-graph-shader.h>
35 #include <dali/internal/render/renderers/render-renderer.h>
36 #include <dali/internal/render/renderers/render-property-buffer.h>
37 #include <dali/internal/update/manager/geometry-batcher.h>
38 #include <dali/internal/update/nodes/scene-graph-layer.h>
42 #if defined(DEBUG_ENABLED)
43 Debug::Filter* gRenderListLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_LISTS");
60 * Function which sorts render items by depth index then by instance
61 * ptrs of shader/geometry/material.
62 * @param[in] lhs Left hand side item
63 * @param[in] rhs Right hand side item
64 * @return True if left item is greater than right
66 bool CompareItems( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
68 // @todo Consider replacing all these sortAttributes with a single long int that
69 // encapsulates the same data (e.g. the middle-order bits of the ptrs).
70 if( lhs.renderItem->mDepthIndex == rhs.renderItem->mDepthIndex )
72 if( lhs.shader == rhs.shader )
74 if( lhs.textureResourceId == rhs.textureResourceId )
76 return lhs.geometry < rhs.geometry;
78 return lhs.textureResourceId < rhs.textureResourceId;
80 return lhs.shader < rhs.shader;
82 return lhs.renderItem->mDepthIndex < rhs.renderItem->mDepthIndex;
86 * Function which sorts render items by clipping hierarchy, then depth index and instance
87 * ptrs of shader/geometry/material.
88 * @param[in] lhs Left hand side item
89 * @param[in] rhs Right hand side item
90 * @return True if left item is greater than right
92 bool CompareItemsWithClipping( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
94 // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
95 if( lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier )
97 return CompareItems( lhs, rhs );
100 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
104 * Function which sorts the render items by Z function, then
105 * by instance ptrs of shader / geometry / material.
106 * @param[in] lhs Left hand side item
107 * @param[in] rhs Right hand side item
108 * @return True if left item is greater than right
110 bool CompareItems3D( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
112 bool lhsIsOpaque = lhs.renderItem->mIsOpaque;
113 if( lhsIsOpaque == rhs.renderItem->mIsOpaque )
117 // If both RenderItems are opaque, sort using shader, then material then geometry.
118 if( lhs.shader == rhs.shader )
120 if( lhs.textureResourceId == rhs.textureResourceId )
122 return lhs.geometry < rhs.geometry;
124 return lhs.textureResourceId < rhs.textureResourceId;
126 return lhs.shader < rhs.shader;
130 // If both RenderItems are transparent, sort using Z, then shader, then material, then geometry.
131 if( Equals( lhs.zValue, rhs.zValue ) )
133 if( lhs.shader == rhs.shader )
135 if( lhs.textureResourceId == rhs.textureResourceId )
137 return lhs.geometry < rhs.geometry;
139 return lhs.textureResourceId < rhs.textureResourceId;
141 return lhs.shader < rhs.shader;
143 return lhs.zValue > rhs.zValue;
153 * Function which sorts render items by clipping hierarchy, then Z function and instance ptrs of shader / geometry / material.
154 * @param[in] lhs Left hand side item
155 * @param[in] rhs Right hand side item
156 * @return True if left item is greater than right
158 bool CompareItems3DWithClipping( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
160 // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
161 if( lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier )
163 return CompareItems3D( lhs, rhs );
166 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
170 * Add a renderer to the list
171 * @param updateBufferIndex to read the model matrix from
172 * @param renderList to add the item to
173 * @param renderable Node-Renderer pair
174 * @param viewMatrix used to calculate modelview matrix for the item
175 * @param camera The camera used to render
176 * @param geometryBatcher The instance of the geometry batcher
177 * @param isLayer3d Whether we are processing a 3D layer or not
178 * @param cull Whether frustum culling is enabled or not
180 inline void AddRendererToRenderList( BufferIndex updateBufferIndex,
181 RenderList& renderList,
182 Renderable& renderable,
183 const Matrix& viewMatrix,
184 SceneGraph::Camera& camera,
185 GeometryBatcher& geometryBatcher,
189 // Discard renderable early if it belongs to the batch which has been consumed in during frame.
190 Node* renderableNode = renderable.mNode;
191 const bool batchingValid( renderable.mRenderer->IsBatchingEnabled() && renderableNode->mBatchIndex != BATCH_NULL_HANDLE );
192 if( batchingValid && geometryBatcher.HasRendered( renderableNode->mBatchIndex ) )
198 const Node* batchParentNode = renderable.mNode->GetBatchParent();
199 const Node* node = ( renderable.mRenderer->IsBatchingEnabled() && batchParentNode ) ?
200 batchParentNode : renderableNode;
202 if( cull && !renderable.mRenderer->GetShader().HintEnabled( Dali::Shader::Hint::MODIFIES_GEOMETRY ) )
204 const Vector4& boundingSphere = node->GetBoundingSphere();
205 inside = ( boundingSphere.w > Math::MACHINE_EPSILON_1000 ) &&
206 ( camera.CheckSphereInFrustum( updateBufferIndex, Vector3( boundingSphere ), boundingSphere.w ) );
213 geometryBatcher.SetRendered( renderableNode->mBatchIndex );
216 Renderer::Opacity opacity = renderable.mRenderer->GetOpacity( updateBufferIndex, *renderable.mNode );
217 if( opacity != Renderer::TRANSPARENT )
219 // Get the next free RenderItem.
220 RenderItem& item = renderList.GetNextFreeItem();
221 item.mRenderer = &renderable.mRenderer->GetRenderer();
222 item.mNode = renderable.mNode;
223 item.mIsOpaque = ( opacity == Renderer::OPAQUE );
224 item.mDepthIndex = renderable.mRenderer->GetDepthIndex();
228 item.mDepthIndex += static_cast<int>( renderable.mNode->GetDepth() ) * Dali::Layer::TREE_DEPTH_MULTIPLIER;
231 // Save ModelView matrix onto the item.
232 node->GetWorldMatrixAndSize( item.mModelMatrix, item.mSize );
234 Matrix::Multiply( item.mModelViewMatrix, item.mModelMatrix, viewMatrix );
240 * Add all renderers to the list
241 * @param updateBufferIndex to read the model matrix from
242 * @param renderList to add the items to
243 * @param renderers to render
244 * NodeRendererContainer Node-Renderer pairs
245 * @param viewMatrix used to calculate modelview matrix for the items
246 * @param camera The camera used to render
247 * @param geometryBatcher The instance of the geometry batcher
248 * @param isLayer3d Whether we are processing a 3D layer or not
249 * @param cull Whether frustum culling is enabled or not
251 inline void AddRenderersToRenderList( BufferIndex updateBufferIndex,
252 RenderList& renderList,
253 RenderableContainer& renderers,
254 const Matrix& viewMatrix,
255 SceneGraph::Camera& camera,
256 GeometryBatcher* geometryBatcher,
260 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "AddRenderersToRenderList()\n");
262 unsigned int rendererCount( renderers.Size() );
263 for( unsigned int i(0); i < rendererCount; ++i )
265 AddRendererToRenderList( updateBufferIndex, renderList, renderers[i], viewMatrix, camera, *geometryBatcher, isLayer3d, cull );
270 * Try to reuse cached RenderItems from the RenderList
271 * This avoids recalculating the model view matrices in case this part of the scene was static
272 * An example case is a toolbar layer that rarely changes or a popup on top of the rest of the stage
273 * @param layer that is being processed
274 * @param renderList that is cached from frame N-1
275 * @param renderables list of renderables
277 inline bool TryReuseCachedRenderers( Layer& layer,
278 RenderList& renderList,
279 RenderableContainer& renderables )
281 bool retValue = false;
282 size_t renderableCount = renderables.Size();
283 // Check that the cached list originates from this layer and that the counts match
284 if( ( renderList.GetSourceLayer() == &layer )&&
285 ( renderList.GetCachedItemCount() == renderableCount ) )
287 // Check that all the same renderers are there. This gives us additional security in avoiding rendering the wrong things.
288 // Render list is sorted so at this stage renderers may be in different order.
289 // Therefore we check a combined sum of all renderer addresses.
290 size_t checkSumNew = 0;
291 size_t checkSumOld = 0;
292 for( size_t index = 0; index < renderableCount; ++index )
294 const Render::Renderer& renderer = renderables[index].mRenderer->GetRenderer();
295 checkSumNew += size_t( &renderer );
296 checkSumOld += size_t( &renderList.GetRenderer( index ) );
298 if( checkSumNew == checkSumOld )
300 // tell list to reuse its existing items
301 renderList.ReuseCachedItems();
308 inline bool SetupRenderList( RenderableContainer& renderables,
310 RenderInstruction& instruction,
311 bool tryReuseRenderList,
312 RenderList** renderList )
314 *renderList = &( instruction.GetNextFreeRenderList( renderables.Size() ) );
315 ( *renderList )->SetClipping( layer.IsClipping(), layer.GetClippingBox() );
316 ( *renderList )->SetSourceLayer( &layer );
318 // Try to reuse cached RenderItems from last time around.
319 return ( tryReuseRenderList && TryReuseCachedRenderers( layer, **renderList, renderables ) );
322 } // Anonymous namespace.
325 RenderInstructionProcessor::RenderInstructionProcessor()
328 // Set up a container of comparators for fast run-time selection.
329 mSortComparitors.Reserve( 4u );
331 mSortComparitors.PushBack( CompareItems );
332 mSortComparitors.PushBack( CompareItemsWithClipping );
333 mSortComparitors.PushBack( CompareItems3D );
334 mSortComparitors.PushBack( CompareItems3DWithClipping );
337 RenderInstructionProcessor::~RenderInstructionProcessor()
341 inline void RenderInstructionProcessor::SortRenderItems( BufferIndex bufferIndex, RenderList& renderList, Layer& layer, bool respectClippingOrder )
343 const size_t renderableCount = renderList.Count();
344 // Reserve space if needed.
345 const unsigned int oldcapacity = mSortingHelper.size();
346 if( oldcapacity < renderableCount )
348 mSortingHelper.reserve( renderableCount );
349 // Add real objects (reserve does not construct objects).
350 mSortingHelper.insert( mSortingHelper.begin() + oldcapacity,
351 (renderableCount - oldcapacity),
352 RenderInstructionProcessor::SortAttributes() );
356 // Clear extra elements from helper, does not decrease capability.
357 mSortingHelper.resize( renderableCount );
360 // Calculate the sorting value, once per item by calling the layers sort function.
361 // Using an if and two for-loops rather than if inside for as its better for branch prediction.
362 if( layer.UsesDefaultSortFunction() )
364 for( size_t index = 0; index < renderableCount; ++index )
366 RenderItem& item = renderList.GetItem( index );
368 item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
370 // The default sorting function should get inlined here.
371 mSortingHelper[ index ].zValue = Internal::Layer::ZValue( item.mModelViewMatrix.GetTranslation3() ) - item.mDepthIndex;
373 // Keep the renderitem pointer in the helper so we can quickly reorder items after sort.
374 mSortingHelper[ index ].renderItem = &item;
379 const Dali::Layer::SortFunctionType sortFunction = layer.GetSortFunction();
380 for( size_t index = 0; index < renderableCount; ++index )
382 RenderItem& item = renderList.GetItem( index );
384 item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
385 mSortingHelper[ index ].zValue = (*sortFunction)( item.mModelViewMatrix.GetTranslation3() ) - item.mDepthIndex;
387 // Keep the RenderItem pointer in the helper so we can quickly reorder items after sort.
388 mSortingHelper[ index ].renderItem = &item;
392 // Here we detemine which comparitor (of the 4) to use.
393 // The comparitors work like a bitmask.
394 // 1 << 0 is added to select a clipping comparitor.
395 // 1 << 1 is added for 3D comparitors.
396 const unsigned int comparitorIndex = ( respectClippingOrder ? ( 1u << 0u ) : 0u ) |
397 ( layer.GetBehavior() == Dali::Layer::LAYER_3D ? ( 1u << 1u ) : 0u );
399 std::stable_sort( mSortingHelper.begin(), mSortingHelper.end(), mSortComparitors[ comparitorIndex ] );
401 // Reorder / re-populate the RenderItems in the RenderList to correct order based on the sortinghelper.
402 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "Sorted Transparent List:\n");
403 RenderItemContainer::Iterator renderListIter = renderList.GetContainer().Begin();
404 for( unsigned int index = 0; index < renderableCount; ++index, ++renderListIter )
406 *renderListIter = mSortingHelper[ index ].renderItem;
407 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, " sortedList[%d] = %p\n", index, mSortingHelper[ index ].renderItem->mRenderer);
411 void RenderInstructionProcessor::Prepare( BufferIndex updateBufferIndex,
412 SortedLayerPointers& sortedLayers,
413 RenderTask& renderTask,
415 GeometryBatcher& geometryBatcher,
416 bool hasClippingNodes,
417 RenderInstructionContainer& instructions )
419 // Retrieve the RenderInstruction buffer from the RenderInstructionContainer
420 // then populate with instructions.
421 RenderInstruction& instruction = instructions.GetNextInstruction( updateBufferIndex );
422 renderTask.PrepareRenderInstruction( instruction, updateBufferIndex );
423 bool viewMatrixHasNotChanged = !renderTask.ViewMatrixUpdated();
425 const Matrix& viewMatrix = renderTask.GetViewMatrix( updateBufferIndex );
426 SceneGraph::Camera& camera = renderTask.GetCamera();
428 const SortedLayersIter endIter = sortedLayers.end();
429 for( SortedLayersIter iter = sortedLayers.begin(); iter != endIter; ++iter )
431 Layer& layer = **iter;
432 const bool tryReuseRenderList( viewMatrixHasNotChanged && layer.CanReuseRenderers( &renderTask.GetCamera() ) );
433 const bool isLayer3D = layer.GetBehavior() == Dali::Layer::LAYER_3D;
434 RenderList* renderList = NULL;
436 if( !layer.colorRenderables.Empty() )
438 RenderableContainer& renderables = layer.colorRenderables;
440 if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
442 renderList->SetHasColorRenderItems( true );
443 AddRenderersToRenderList( updateBufferIndex, *renderList, renderables, viewMatrix, camera, &geometryBatcher, isLayer3D, cull );
445 // We only use the clipping version of the sort comparitor if any clipping nodes exist within the RenderList.
446 SortRenderItems( updateBufferIndex, *renderList, layer, hasClippingNodes );
450 if( !layer.overlayRenderables.Empty() )
452 RenderableContainer& renderables = layer.overlayRenderables;
454 if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
456 renderList->SetHasColorRenderItems( false );
457 AddRenderersToRenderList( updateBufferIndex, *renderList, renderables, viewMatrix, camera, NULL, isLayer3D, cull );
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();