2 * Copyright (c) 2020 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/update/nodes/scene-graph-layer.h>
38 #if defined(DEBUG_ENABLED)
39 Debug::Filter* gRenderListLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_LISTS");
56 * Function which compares render items by shader/textureSet/geometry
57 * @param[in] lhs Left hand side item
58 * @param[in] rhs Right hand side item
59 * @return True if left item is greater than right
61 inline bool PartialCompareItems( const RenderInstructionProcessor::SortAttributes& lhs,
62 const RenderInstructionProcessor::SortAttributes& rhs )
64 if( lhs.shader == rhs.shader )
66 if( lhs.textureSet == rhs.textureSet )
68 return lhs.geometry < rhs.geometry;
70 return lhs.textureSet < rhs.textureSet;
72 return lhs.shader < rhs.shader;
76 * Function which sorts render items by depth index then by instance
77 * ptrs of shader/textureSet/geometry.
78 * @param[in] lhs Left hand side item
79 * @param[in] rhs Right hand side item
80 * @return True if left item is greater than right
82 bool CompareItems( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
84 // @todo Consider replacing all these sortAttributes with a single long int that
85 // encapsulates the same data (e.g. the middle-order bits of the ptrs).
86 if( lhs.renderItem->mDepthIndex == rhs.renderItem->mDepthIndex )
88 return PartialCompareItems( lhs, rhs );
90 return lhs.renderItem->mDepthIndex < rhs.renderItem->mDepthIndex;
94 * Function which sorts the render items by Z function, then
95 * by instance ptrs of shader / geometry / material.
96 * @param[in] lhs Left hand side item
97 * @param[in] rhs Right hand side item
98 * @return True if left item is greater than right
100 bool CompareItems3D( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
102 const bool lhsIsOpaque = lhs.renderItem->mIsOpaque;
103 if( lhsIsOpaque == rhs.renderItem->mIsOpaque )
107 // If both RenderItems are opaque, sort using shader, then material then geometry.
108 return PartialCompareItems( lhs, rhs );
112 // If both RenderItems are transparent, sort using Z, then shader, then material, then geometry.
113 if( Equals( lhs.zValue, rhs.zValue ) )
115 return PartialCompareItems( lhs, rhs );
117 return lhs.zValue > rhs.zValue;
127 * Function which sorts render items by clipping hierarchy, then Z function and instance ptrs of shader / geometry / material.
128 * @param[in] lhs Left hand side item
129 * @param[in] rhs Right hand side item
130 * @return True if left item is greater than right
132 bool CompareItems3DWithClipping( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
134 // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
135 if( lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier )
137 return CompareItems3D( lhs, rhs );
140 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
144 * Add a renderer to the list
145 * @param updateBufferIndex to read the model matrix from
146 * @param renderList to add the item to
147 * @param renderable Node-Renderer pair
148 * @param viewMatrix used to calculate modelview matrix for the item
149 * @param camera The camera used to render
150 * @param isLayer3d Whether we are processing a 3D layer or not
151 * @param cull Whether frustum culling is enabled or not
153 inline void AddRendererToRenderList(BufferIndex updateBufferIndex,
154 RenderList& renderList,
155 Renderable& renderable,
156 const Matrix& viewMatrix,
157 SceneGraph::Camera& camera,
162 Node* node = renderable.mNode;
164 if (cull && renderable.mRenderer && !renderable.mRenderer->GetShader().HintEnabled(Dali::Shader::Hint::MODIFIES_GEOMETRY))
166 const Vector4& boundingSphere = node->GetBoundingSphere();
167 inside = (boundingSphere.w > Math::MACHINE_EPSILON_1000) &&
168 (camera.CheckSphereInFrustum(updateBufferIndex, Vector3(boundingSphere), boundingSphere.w));
173 Renderer::OpacityType opacityType = renderable.mRenderer ? renderable.mRenderer->GetOpacityType( updateBufferIndex, *renderable.mNode ) : Renderer::OPAQUE;
174 if (opacityType != Renderer::TRANSPARENT || node->GetClippingMode() == ClippingMode::CLIP_CHILDREN)
176 // Get the next free RenderItem.
177 RenderItem& item = renderList.GetNextFreeItem();
180 auto& partialRenderingData = node->GetPartialRenderingData();
182 auto& partialRenderingCacheInfo = node->GetPartialRenderingData().GetCurrentCacheInfo();
184 partialRenderingCacheInfo.node = node;
185 partialRenderingCacheInfo.isOpaque = (opacityType == Renderer::OPAQUE);
186 partialRenderingCacheInfo.renderer = renderable.mRenderer;
187 partialRenderingCacheInfo.color = renderable.mNode->GetColor(updateBufferIndex);
188 partialRenderingCacheInfo.depthIndex = renderable.mNode->GetDepthIndex();
190 if( renderable.mRenderer )
192 partialRenderingCacheInfo.textureSet = renderable.mRenderer->GetTextures();
195 item.mNode = renderable.mNode;
196 item.mIsOpaque = (opacityType == Renderer::OPAQUE);
197 item.mColor = renderable.mNode->GetColor(updateBufferIndex);
199 item.mDepthIndex = 0;
202 item.mDepthIndex = renderable.mNode->GetDepthIndex();
205 if (DALI_LIKELY(renderable.mRenderer))
207 item.mRenderer = &renderable.mRenderer->GetRenderer();
208 item.mTextureSet = renderable.mRenderer->GetTextures();
209 item.mDepthIndex += renderable.mRenderer->GetDepthIndex();
213 item.mRenderer = nullptr;
216 item.mIsUpdated |= isLayer3d;
218 // Save ModelView matrix onto the item.
219 node->GetWorldMatrixAndSize( item.mModelMatrix, item.mSize );
220 Matrix::Multiply( item.mModelViewMatrix, item.mModelMatrix, viewMatrix );
222 partialRenderingCacheInfo.matrix = item.mModelViewMatrix;
223 partialRenderingCacheInfo.size = item.mSize;
225 if (renderable.mNode->GetUpdateSizeHint() == Vector3::ZERO)
227 // RenderItem::CalculateViewportSpaceAABB cannot cope with z transform
228 // I don't use item.mModelMatrix.GetTransformComponents() for z transform, would be to slow
229 if (!isLayer3d && item.mModelMatrix.GetZAxis() == Vector3(0.0f, 0.0f, 1.0f))
231 item.mUpdateSize = item.mSize;
236 item.mUpdateSize = renderable.mNode->GetUpdateSizeHint();
239 partialRenderingCacheInfo.updatedSize = item.mUpdateSize;
241 item.mIsUpdated = partialRenderingData.IsUpdated() || item.mIsUpdated;
242 partialRenderingData.SwapBuffers();
244 node->SetCulled( updateBufferIndex, false );
248 node->SetCulled( updateBufferIndex, true );
253 * Add all renderers to the list
254 * @param updateBufferIndex to read the model matrix from
255 * @param renderList to add the items to
256 * @param renderers to render
257 * NodeRendererContainer Node-Renderer pairs
258 * @param viewMatrix used to calculate modelview matrix for the items
259 * @param camera The camera used to render
260 * @param isLayer3d Whether we are processing a 3D layer or not
261 * @param cull Whether frustum culling is enabled or not
263 inline void AddRenderersToRenderList( BufferIndex updateBufferIndex,
264 RenderList& renderList,
265 RenderableContainer& renderers,
266 const Matrix& viewMatrix,
267 SceneGraph::Camera& camera,
271 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "AddRenderersToRenderList()\n");
273 for( auto&& renderer : renderers )
275 AddRendererToRenderList( updateBufferIndex,
286 * Try to reuse cached RenderItems from the RenderList
287 * This avoids recalculating the model view matrices in case this part of the scene was static
288 * An example case is a toolbar layer that rarely changes or a popup on top of the rest of the stage
289 * @param layer that is being processed
290 * @param renderList that is cached from frame N-1
291 * @param renderables list of renderables
293 inline bool TryReuseCachedRenderers( Layer& layer,
294 RenderList& renderList,
295 RenderableContainer& renderables )
297 bool retValue = false;
298 uint32_t renderableCount = static_cast<uint32_t>( renderables.Size() );
299 // Check that the cached list originates from this layer and that the counts match
300 if( ( renderList.GetSourceLayer() == &layer )&&
301 ( renderList.GetCachedItemCount() == renderableCount ) )
303 // Check that all the same renderers are there. This gives us additional security in avoiding rendering the wrong things.
304 // Render list is sorted so at this stage renderers may be in different order.
305 // Therefore we check a combined sum of all renderer addresses.
306 size_t checkSumNew = 0;
307 size_t checkSumOld = 0;
308 for( uint32_t index = 0; index < renderableCount; ++index )
310 const Render::Renderer& renderer = renderables[index].mRenderer->GetRenderer();
311 checkSumNew += reinterpret_cast<std::size_t>( &renderer );
312 checkSumOld += reinterpret_cast<std::size_t>( &renderList.GetRenderer( index ) );
314 if( checkSumNew == checkSumOld )
316 // tell list to reuse its existing items
317 renderList.ReuseCachedItems();
325 inline bool SetupRenderList( RenderableContainer& renderables,
327 RenderInstruction& instruction,
328 bool tryReuseRenderList,
329 RenderList** renderList )
331 *renderList = &( instruction.GetNextFreeRenderList( renderables.Size() ) );
332 ( *renderList )->SetClipping( layer.IsClipping(), layer.GetClippingBox() );
333 ( *renderList )->SetSourceLayer( &layer );
335 // Try to reuse cached RenderItems from last time around.
336 return ( tryReuseRenderList && TryReuseCachedRenderers( layer, **renderList, renderables ) );
339 } // Anonymous namespace.
342 RenderInstructionProcessor::RenderInstructionProcessor()
345 // Set up a container of comparators for fast run-time selection.
346 mSortComparitors.Reserve( 3u );
348 mSortComparitors.PushBack( CompareItems );
349 mSortComparitors.PushBack( CompareItems3D );
350 mSortComparitors.PushBack( CompareItems3DWithClipping );
353 RenderInstructionProcessor::~RenderInstructionProcessor() = default;
355 inline void RenderInstructionProcessor::SortRenderItems( BufferIndex bufferIndex, RenderList& renderList, Layer& layer, bool respectClippingOrder )
357 const uint32_t renderableCount = static_cast<uint32_t>( renderList.Count() );
358 // Reserve space if needed.
359 const uint32_t oldcapacity = static_cast<uint32_t>( mSortingHelper.size() );
360 if( oldcapacity < renderableCount )
362 mSortingHelper.reserve( renderableCount );
363 // Add real objects (reserve does not construct objects).
364 mSortingHelper.insert( mSortingHelper.begin() + oldcapacity,
365 (renderableCount - oldcapacity),
366 RenderInstructionProcessor::SortAttributes() );
370 // Clear extra elements from helper, does not decrease capability.
371 mSortingHelper.resize( renderableCount );
374 // Calculate the sorting value, once per item by calling the layers sort function.
375 // Using an if and two for-loops rather than if inside for as its better for branch prediction.
376 if( layer.UsesDefaultSortFunction() )
378 for( uint32_t index = 0; index < renderableCount; ++index )
380 RenderItem& item = renderList.GetItem( index );
384 item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
388 mSortingHelper[ index ].textureSet = item.mTextureSet;
390 // The default sorting function should get inlined here.
391 mSortingHelper[ index ].zValue = Internal::Layer::ZValue( item.mModelViewMatrix.GetTranslation3() ) - static_cast<float>( item.mDepthIndex );
393 // Keep the renderitem pointer in the helper so we can quickly reorder items after sort.
394 mSortingHelper[ index ].renderItem = &item;
399 const Dali::Layer::SortFunctionType sortFunction = layer.GetSortFunction();
400 for( uint32_t index = 0; index < renderableCount; ++index )
402 RenderItem& item = renderList.GetItem( index );
404 item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
407 mSortingHelper[ index ].textureSet = item.mTextureSet;
410 mSortingHelper[ index ].zValue = (*sortFunction)( item.mModelViewMatrix.GetTranslation3() ) - static_cast<float>( item.mDepthIndex );
412 // Keep the RenderItem pointer in the helper so we can quickly reorder items after sort.
413 mSortingHelper[ index ].renderItem = &item;
417 // Here we determine which comparitor (of the 3) to use.
420 // 2 is LAYER_3D + Clipping
421 const unsigned int comparitorIndex = layer.GetBehavior() == Dali::Layer::LAYER_3D ? respectClippingOrder ? 2u : 1u : 0u;
423 std::stable_sort( mSortingHelper.begin(), mSortingHelper.end(), mSortComparitors[ comparitorIndex ] );
425 // Reorder / re-populate the RenderItems in the RenderList to correct order based on the sortinghelper.
426 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "Sorted Transparent List:\n");
427 RenderItemContainer::Iterator renderListIter = renderList.GetContainer().Begin();
428 for( uint32_t index = 0; index < renderableCount; ++index, ++renderListIter )
430 *renderListIter = mSortingHelper[ index ].renderItem;
431 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, " sortedList[%d] = %p\n", index, mSortingHelper[ index ].renderItem->mRenderer);
435 void RenderInstructionProcessor::Prepare( BufferIndex updateBufferIndex,
436 SortedLayerPointers& sortedLayers,
437 RenderTask& renderTask,
439 bool hasClippingNodes,
440 RenderInstructionContainer& instructions )
442 // Retrieve the RenderInstruction buffer from the RenderInstructionContainer
443 // then populate with instructions.
444 RenderInstruction& instruction = renderTask.PrepareRenderInstruction( updateBufferIndex );
445 bool viewMatrixHasNotChanged = !renderTask.ViewMatrixUpdated();
446 bool isRenderListAdded = false;
447 bool isRootLayerDirty = false;
449 const Matrix& viewMatrix = renderTask.GetViewMatrix( updateBufferIndex );
450 SceneGraph::Camera& camera = renderTask.GetCamera();
452 const SortedLayersIter endIter = sortedLayers.end();
453 for( SortedLayersIter iter = sortedLayers.begin(); iter != endIter; ++iter )
455 Layer& layer = **iter;
456 const bool tryReuseRenderList( viewMatrixHasNotChanged && layer.CanReuseRenderers( &renderTask.GetCamera() ) );
457 const bool isLayer3D = layer.GetBehavior() == Dali::Layer::LAYER_3D;
458 RenderList* renderList = nullptr;
460 if( layer.IsRoot() && ( layer.GetDirtyFlags() != NodePropertyFlags::NOTHING ) )
462 // If root-layer & dirty, i.e. a property has changed or a child has been deleted, then we need to ensure we render once more
463 isRootLayerDirty = true;
466 if( !layer.colorRenderables.Empty() )
468 RenderableContainer& renderables = layer.colorRenderables;
470 if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
472 renderList->SetHasColorRenderItems( true );
473 AddRenderersToRenderList( updateBufferIndex,
481 // We only use the clipping version of the sort comparitor if any clipping nodes exist within the RenderList.
482 SortRenderItems( updateBufferIndex, *renderList, layer, hasClippingNodes );
485 isRenderListAdded = true;
488 if( !layer.overlayRenderables.Empty() )
490 RenderableContainer& renderables = layer.overlayRenderables;
492 if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
494 renderList->SetHasColorRenderItems( false );
495 AddRenderersToRenderList( updateBufferIndex,
503 // Clipping hierarchy is irrelevant when sorting overlay items, so we specify using the non-clipping version of the sort comparitor.
504 SortRenderItems( updateBufferIndex, *renderList, layer, false );
507 isRenderListAdded = true;
511 // Inform the render instruction that all renderers have been added and this frame is complete.
512 instruction.UpdateCompleted();
514 if( isRenderListAdded || instruction.mIsClearColorSet || isRootLayerDirty )
516 instructions.PushBack( updateBufferIndex, &instruction );