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/nodes/scene-graph-layer.h>
41 #if defined(DEBUG_ENABLED)
42 Debug::Filter* gRenderListLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_LISTS");
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
65 bool CompareItems( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
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 )
71 if( lhs.shader == rhs.shader )
73 if( lhs.textureResourceId == rhs.textureResourceId )
75 return lhs.geometry < rhs.geometry;
77 return lhs.textureResourceId < rhs.textureResourceId;
79 return lhs.shader < rhs.shader;
81 return lhs.renderItem->mDepthIndex < rhs.renderItem->mDepthIndex;
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
91 bool CompareItemsWithClipping( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
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 )
96 return CompareItems( lhs, rhs );
99 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
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
109 bool CompareItems3D( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
111 bool lhsIsOpaque = lhs.renderItem->mIsOpaque;
112 if( lhsIsOpaque == rhs.renderItem->mIsOpaque )
116 // If both RenderItems are opaque, sort using shader, then material then geometry.
117 if( lhs.shader == rhs.shader )
119 if( lhs.textureResourceId == rhs.textureResourceId )
121 return lhs.geometry < rhs.geometry;
123 return lhs.textureResourceId < rhs.textureResourceId;
125 return lhs.shader < rhs.shader;
129 // If both RenderItems are transparent, sort using Z, then shader, then material, then geometry.
130 if( Equals( lhs.zValue, rhs.zValue ) )
132 if( lhs.shader == rhs.shader )
134 if( lhs.textureResourceId == rhs.textureResourceId )
136 return lhs.geometry < rhs.geometry;
138 return lhs.textureResourceId < rhs.textureResourceId;
140 return lhs.shader < rhs.shader;
142 return lhs.zValue > rhs.zValue;
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
157 bool CompareItems3DWithClipping( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
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 )
162 return CompareItems3D( lhs, rhs );
165 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
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 isLayer3d Whether we are processing a 3D layer or not
176 * @param cull Whether frustum culling is enabled or not
178 inline void AddRendererToRenderList( BufferIndex updateBufferIndex,
179 RenderList& renderList,
180 Renderable& renderable,
181 const Matrix& viewMatrix,
182 SceneGraph::Camera& camera,
187 if ( cull && !renderable.mRenderer->GetShader().HintEnabled( Dali::Shader::Hint::MODIFIES_GEOMETRY ) )
189 const Vector4& boundingSphere = renderable.mNode->GetBoundingSphere();
190 inside = (boundingSphere.w > Math::MACHINE_EPSILON_1000) &&
191 (camera.CheckSphereInFrustum( updateBufferIndex, Vector3(boundingSphere), boundingSphere.w ) );
196 Renderer::Opacity opacity = renderable.mRenderer->GetOpacity( updateBufferIndex, *renderable.mNode );
197 if( opacity != Renderer::TRANSPARENT )
199 // Get the next free RenderItem.
200 RenderItem& item = renderList.GetNextFreeItem();
201 item.mRenderer = &renderable.mRenderer->GetRenderer();
202 item.mNode = renderable.mNode;
203 item.mIsOpaque = ( opacity == Renderer::OPAQUE );
204 item.mDepthIndex = renderable.mRenderer->GetDepthIndex();
208 item.mDepthIndex += static_cast<int>( renderable.mNode->GetDepth() ) * Dali::Layer::TREE_DEPTH_MULTIPLIER;
211 // Save ModelView matrix onto the item.
212 renderable.mNode->GetWorldMatrixAndSize( item.mModelMatrix, item.mSize );
213 Matrix::Multiply( item.mModelViewMatrix, item.mModelMatrix, viewMatrix );
219 * Add all renderers to the list
220 * @param updateBufferIndex to read the model matrix from
221 * @param renderList to add the items to
222 * @param renderers to render
223 * NodeRendererContainer Node-Renderer pairs
224 * @param viewMatrix used to calculate modelview matrix for the items
225 * @param camera The camera used to render
226 * @param isLayer3d Whether we are processing a 3D layer or not
227 * @param cull Whether frustum culling is enabled or not
229 inline void AddRenderersToRenderList( BufferIndex updateBufferIndex,
230 RenderList& renderList,
231 RenderableContainer& renderers,
232 const Matrix& viewMatrix,
233 SceneGraph::Camera& camera,
237 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "AddRenderersToRenderList()\n");
239 unsigned int rendererCount( renderers.Size() );
240 for( unsigned int i(0); i < rendererCount; ++i )
242 AddRendererToRenderList( updateBufferIndex, renderList, renderers[i], viewMatrix, camera, isLayer3d, cull );
247 * Try to reuse cached RenderItems from the RenderList
248 * This avoids recalculating the model view matrices in case this part of the scene was static
249 * An example case is a toolbar layer that rarely changes or a popup on top of the rest of the stage
250 * @param layer that is being processed
251 * @param renderList that is cached from frame N-1
252 * @param renderables list of renderables
254 inline bool TryReuseCachedRenderers( Layer& layer,
255 RenderList& renderList,
256 RenderableContainer& renderables )
258 bool retValue = false;
259 size_t renderableCount = renderables.Size();
260 // Check that the cached list originates from this layer and that the counts match
261 if( ( renderList.GetSourceLayer() == &layer )&&
262 ( renderList.GetCachedItemCount() == renderableCount ) )
264 // Check that all the same renderers are there. This gives us additional security in avoiding rendering the wrong things.
265 // Render list is sorted so at this stage renderers may be in different order.
266 // Therefore we check a combined sum of all renderer addresses.
267 size_t checkSumNew = 0;
268 size_t checkSumOld = 0;
269 for( size_t index = 0; index < renderableCount; ++index )
271 const Render::Renderer& renderer = renderables[index].mRenderer->GetRenderer();
272 checkSumNew += size_t( &renderer );
273 checkSumOld += size_t( &renderList.GetRenderer( index ) );
275 if( checkSumNew == checkSumOld )
277 // tell list to reuse its existing items
278 renderList.ReuseCachedItems();
285 inline bool SetupRenderList( RenderableContainer& renderables,
287 RenderInstruction& instruction,
288 bool tryReuseRenderList,
289 RenderList** renderList )
291 *renderList = &( instruction.GetNextFreeRenderList( renderables.Size() ) );
292 ( *renderList )->SetClipping( layer.IsClipping(), layer.GetClippingBox() );
293 ( *renderList )->SetSourceLayer( &layer );
295 // Try to reuse cached RenderItems from last time around.
296 return ( tryReuseRenderList && TryReuseCachedRenderers( layer, **renderList, renderables ) );
299 } // Anonymous namespace.
302 RenderInstructionProcessor::RenderInstructionProcessor()
305 // Set up a container of comparators for fast run-time selection.
306 mSortComparitors.Reserve( 4u );
308 mSortComparitors.PushBack( CompareItems );
309 mSortComparitors.PushBack( CompareItemsWithClipping );
310 mSortComparitors.PushBack( CompareItems3D );
311 mSortComparitors.PushBack( CompareItems3DWithClipping );
314 RenderInstructionProcessor::~RenderInstructionProcessor()
318 inline void RenderInstructionProcessor::SortRenderItems( BufferIndex bufferIndex, RenderList& renderList, Layer& layer, bool respectClippingOrder )
320 const size_t renderableCount = renderList.Count();
321 // Reserve space if needed.
322 const unsigned int oldcapacity = mSortingHelper.size();
323 if( oldcapacity < renderableCount )
325 mSortingHelper.reserve( renderableCount );
326 // Add real objects (reserve does not construct objects).
327 mSortingHelper.insert( mSortingHelper.begin() + oldcapacity,
328 (renderableCount - oldcapacity),
329 RenderInstructionProcessor::SortAttributes() );
333 // Clear extra elements from helper, does not decrease capability.
334 mSortingHelper.resize( renderableCount );
337 // Calculate the sorting value, once per item by calling the layers sort function.
338 // Using an if and two for-loops rather than if inside for as its better for branch prediction.
339 if( layer.UsesDefaultSortFunction() )
341 for( size_t index = 0; index < renderableCount; ++index )
343 RenderItem& item = renderList.GetItem( index );
345 item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
347 // The default sorting function should get inlined here.
348 mSortingHelper[ index ].zValue = Internal::Layer::ZValue( item.mModelViewMatrix.GetTranslation3() ) - item.mDepthIndex;
350 // Keep the renderitem pointer in the helper so we can quickly reorder items after sort.
351 mSortingHelper[ index ].renderItem = &item;
356 const Dali::Layer::SortFunctionType sortFunction = layer.GetSortFunction();
357 for( size_t index = 0; index < renderableCount; ++index )
359 RenderItem& item = renderList.GetItem( index );
361 item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
362 mSortingHelper[ index ].zValue = (*sortFunction)( item.mModelViewMatrix.GetTranslation3() ) - item.mDepthIndex;
364 // Keep the RenderItem pointer in the helper so we can quickly reorder items after sort.
365 mSortingHelper[ index ].renderItem = &item;
369 // Here we detemine which comparitor (of the 4) to use.
370 // The comparitors work like a bitmask.
371 // 1 << 0 is added to select a clipping comparitor.
372 // 1 << 1 is added for 3D comparitors.
373 const unsigned int comparitorIndex = ( respectClippingOrder ? ( 1u << 0u ) : 0u ) |
374 ( layer.GetBehavior() == Dali::Layer::LAYER_3D ? ( 1u << 1u ) : 0u );
376 std::stable_sort( mSortingHelper.begin(), mSortingHelper.end(), mSortComparitors[ comparitorIndex ] );
378 // Reorder / re-populate the RenderItems in the RenderList to correct order based on the sortinghelper.
379 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "Sorted Transparent List:\n");
380 RenderItemContainer::Iterator renderListIter = renderList.GetContainer().Begin();
381 for( unsigned int index = 0; index < renderableCount; ++index, ++renderListIter )
383 *renderListIter = mSortingHelper[ index ].renderItem;
384 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, " sortedList[%d] = %p\n", index, mSortingHelper[ index ].renderItem->mRenderer);
388 void RenderInstructionProcessor::Prepare( BufferIndex updateBufferIndex,
389 SortedLayerPointers& sortedLayers,
390 RenderTask& renderTask,
392 bool hasClippingNodes,
393 RenderInstructionContainer& instructions )
395 // Retrieve the RenderInstruction buffer from the RenderInstructionContainer
396 // then populate with instructions.
397 RenderInstruction& instruction = instructions.GetNextInstruction( updateBufferIndex );
398 renderTask.PrepareRenderInstruction( instruction, updateBufferIndex );
399 bool viewMatrixHasNotChanged = !renderTask.ViewMatrixUpdated();
401 const Matrix& viewMatrix = renderTask.GetViewMatrix( updateBufferIndex );
402 SceneGraph::Camera& camera = renderTask.GetCamera();
404 const SortedLayersIter endIter = sortedLayers.end();
405 for( SortedLayersIter iter = sortedLayers.begin(); iter != endIter; ++iter )
407 Layer& layer = **iter;
408 const bool tryReuseRenderList( viewMatrixHasNotChanged && layer.CanReuseRenderers( &renderTask.GetCamera() ) );
409 const bool isLayer3D = layer.GetBehavior() == Dali::Layer::LAYER_3D;
410 RenderList* renderList = NULL;
412 if( !layer.colorRenderables.Empty() )
414 RenderableContainer& renderables = layer.colorRenderables;
416 if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
418 renderList->SetHasColorRenderItems( true );
419 AddRenderersToRenderList( updateBufferIndex, *renderList, renderables, viewMatrix, camera, isLayer3D, cull );
421 // We only use the clipping version of the sort comparitor if any clipping nodes exist within the RenderList.
422 SortRenderItems( updateBufferIndex, *renderList, layer, hasClippingNodes );
426 if( !layer.overlayRenderables.Empty() )
428 RenderableContainer& renderables = layer.overlayRenderables;
430 if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
432 renderList->SetHasColorRenderItems( false );
433 AddRenderersToRenderList( updateBufferIndex, *renderList, renderables, viewMatrix, camera, isLayer3D, cull );
435 // Clipping hierarchy is irrelevant when sorting overlay items, so we specify using the non-clipping version of the sort comparitor.
436 SortRenderItems( updateBufferIndex, *renderList, layer, false );
441 // Inform the render instruction that all renderers have been added and this frame is complete.
442 instruction.UpdateCompleted();