2 * Copyright (c) 2022 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/integration-api/debug.h>
23 #include <dali/internal/event/actors/layer-impl.h> // for the default sorting function
24 #include <dali/internal/render/common/render-instruction-container.h>
25 #include <dali/internal/render/common/render-instruction.h>
26 #include <dali/internal/render/common/render-item.h>
27 #include <dali/internal/render/common/render-tracker.h>
28 #include <dali/internal/render/renderers/render-renderer.h>
29 #include <dali/internal/render/shaders/render-shader.h>
30 #include <dali/internal/update/manager/sorted-layers.h>
31 #include <dali/internal/update/nodes/scene-graph-layer.h>
32 #include <dali/internal/update/render-tasks/scene-graph-render-task.h>
33 #include <dali/internal/update/rendering/scene-graph-texture-set.h>
34 #include <dali/public-api/actors/layer.h>
38 #if defined(DEBUG_ENABLED)
39 Debug::Filter* gRenderListLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_LISTS");
52 * Function which compares render items by shader/textureSet/geometry
53 * @param[in] lhs Left hand side item
54 * @param[in] rhs Right hand side item
55 * @return True if left item is greater than right
57 inline bool PartialCompareItems(const RenderInstructionProcessor::SortAttributes& lhs,
58 const RenderInstructionProcessor::SortAttributes& rhs)
60 if(lhs.shader == rhs.shader)
62 if(lhs.textureSet == rhs.textureSet)
64 return lhs.geometry < rhs.geometry;
66 return lhs.textureSet < rhs.textureSet;
68 return lhs.shader < rhs.shader;
72 * Function which sorts render items by depth index then by instance
73 * ptrs of shader/textureSet/geometry.
74 * @param[in] lhs Left hand side item
75 * @param[in] rhs Right hand side item
76 * @return True if left item is greater than right
78 bool CompareItems(const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs)
80 // @todo Consider replacing all these sortAttributes with a single long int that
81 // encapsulates the same data (e.g. the middle-order bits of the ptrs).
82 if(lhs.renderItem->mDepthIndex == rhs.renderItem->mDepthIndex)
84 return PartialCompareItems(lhs, rhs);
86 return lhs.renderItem->mDepthIndex < rhs.renderItem->mDepthIndex;
90 * Function which sorts the render items by Z function, then
91 * by instance ptrs of shader / geometry / material.
92 * @param[in] lhs Left hand side item
93 * @param[in] rhs Right hand side item
94 * @return True if left item is greater than right
96 bool CompareItems3D(const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs)
98 const bool lhsIsOpaque = lhs.renderItem->mIsOpaque;
99 if(lhsIsOpaque == rhs.renderItem->mIsOpaque)
103 // If both RenderItems are opaque, sort using shader, then material then geometry.
104 return PartialCompareItems(lhs, rhs);
108 // If both RenderItems are transparent, sort using Z, then shader, then material, then geometry.
109 if(Equals(lhs.zValue, rhs.zValue))
111 return PartialCompareItems(lhs, rhs);
113 return lhs.zValue > rhs.zValue;
123 * Function which sorts render items by clipping hierarchy, then Z function and instance ptrs of shader / geometry / material.
124 * @param[in] lhs Left hand side item
125 * @param[in] rhs Right hand side item
126 * @return True if left item is greater than right
128 bool CompareItems3DWithClipping(const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs)
130 // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
131 if(lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier)
133 return CompareItems3D(lhs, rhs);
136 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
140 * Set the update size of the node
141 * @param[in] node The node of the renderer
142 * @param[in] isLayer3d Whether we are processing a 3D layer or not
143 * @param[in,out] nodeWorldMatrix The world matrix of the node
144 * @param[in,out] nodeSize The size of the node
145 * @param[in,out] nodeUpdateSize The update size of the node
147 inline void SetNodeUpdateSize(Node* node, bool isLayer3d, Matrix& nodeWorldMatrix, Vector3& nodeSize, Vector3& nodeUpdateSize)
149 node->GetWorldMatrixAndSize(nodeWorldMatrix, nodeSize);
151 if(node->GetUpdateSizeHint() == Vector3::ZERO)
153 // RenderItem::CalculateViewportSpaceAABB cannot cope with z transform
154 // I don't use item.mModelMatrix.GetTransformComponents() for z transform, would be too slow
155 if(!isLayer3d && nodeWorldMatrix.GetZAxis() == Vector3(0.0f, 0.0f, 1.0f))
157 nodeUpdateSize = nodeSize;
162 nodeUpdateSize = node->GetUpdateSizeHint();
167 * Add a renderer to the list
168 * @param updateBufferIndex to read the model matrix from
169 * @param renderList to add the item to
170 * @param renderable Node-Renderer pair
171 * @param viewMatrix used to calculate modelview matrix for the item
172 * @param camera The camera used to render
173 * @param isLayer3d Whether we are processing a 3D layer or not
174 * @param viewportSet Whether the viewport is set or not
175 * @param viewport The viewport
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,
185 const Viewport& viewport,
189 Node* node = renderable.mNode;
190 Matrix nodeWorldMatrix(false);
192 Vector3 nodeUpdateSize;
193 bool nodeUpdateSizeSet(false);
194 Matrix nodeModelViewMatrix(false);
195 bool nodeModelViewMatrixSet(false);
197 // Don't cull items which have render callback
198 bool hasRenderCallback = (renderable.mRenderer && renderable.mRenderer->GetRenderCallback());
200 if(cull && renderable.mRenderer && (hasRenderCallback || (!renderable.mRenderer->GetShader().HintEnabled(Dali::Shader::Hint::MODIFIES_GEOMETRY) && node->GetClippingMode() == ClippingMode::DISABLED)))
202 const Vector4& boundingSphere = node->GetBoundingSphere();
203 inside = (boundingSphere.w > Math::MACHINE_EPSILON_1000) &&
204 (camera.CheckSphereInFrustum(updateBufferIndex, Vector3(boundingSphere), boundingSphere.w));
206 if(inside && !isLayer3d && viewportSet)
208 SetNodeUpdateSize(node, isLayer3d, nodeWorldMatrix, nodeSize, nodeUpdateSize);
209 nodeUpdateSizeSet = true;
211 const Vector3& scale = node->GetWorldScale(updateBufferIndex);
212 const Vector3& halfSize = nodeUpdateSize * scale * 0.5f;
213 float radius(halfSize.Length());
215 if(radius > Math::MACHINE_EPSILON_1000)
217 Matrix::Multiply(nodeModelViewMatrix, nodeWorldMatrix, viewMatrix);
218 nodeModelViewMatrixSet = true;
220 ClippingBox clippingBox = RenderItem::CalculateViewportSpaceAABB(nodeModelViewMatrix, nodeUpdateSize, viewport.width, viewport.height);
221 inside = clippingBox.Intersects(viewport);
228 bool skipRender(false);
229 bool isOpaque = true;
230 if(!hasRenderCallback)
232 Renderer::OpacityType opacityType = renderable.mRenderer ? renderable.mRenderer->GetOpacityType(updateBufferIndex, *node) : Renderer::OPAQUE;
234 // We can skip render when node is not clipping and transparent
235 skipRender = (opacityType == Renderer::TRANSPARENT && node->GetClippingMode() == ClippingMode::DISABLED);
237 isOpaque = (opacityType == Renderer::OPAQUE);
242 // Get the next free RenderItem.
243 RenderItem& item = renderList.GetNextFreeItem();
246 auto& partialRenderingData = node->GetPartialRenderingData();
248 auto& partialRenderingCacheInfo = node->GetPartialRenderingData().GetCurrentCacheInfo();
250 partialRenderingCacheInfo.node = node;
251 partialRenderingCacheInfo.isOpaque = isOpaque;
252 partialRenderingCacheInfo.renderer = renderable.mRenderer;
253 partialRenderingCacheInfo.color = node->GetWorldColor(updateBufferIndex);
254 partialRenderingCacheInfo.depthIndex = node->GetDepthIndex();
256 if(DALI_LIKELY(renderable.mRenderer))
258 partialRenderingCacheInfo.textureSet = renderable.mRenderer->GetTextureSet();
262 item.mIsOpaque = isOpaque;
263 item.mColor = node->GetColor(updateBufferIndex);
265 item.mDepthIndex = 0;
268 item.mDepthIndex = node->GetDepthIndex();
271 if(DALI_LIKELY(renderable.mRenderer))
273 item.mRenderer = &renderable.mRenderer->GetRenderer();
274 item.mTextureSet = renderable.mRenderer->GetTextureSet();
275 item.mDepthIndex += renderable.mRenderer->GetDepthIndex();
279 item.mRenderer = nullptr;
282 item.mIsUpdated |= isLayer3d;
284 if(!nodeUpdateSizeSet)
286 SetNodeUpdateSize(node, isLayer3d, nodeWorldMatrix, nodeSize, nodeUpdateSize);
289 item.mSize = nodeSize;
290 item.mUpdateSize = nodeUpdateSize;
291 item.mModelMatrix = nodeWorldMatrix;
293 if(!nodeModelViewMatrixSet)
295 Matrix::Multiply(nodeModelViewMatrix, nodeWorldMatrix, viewMatrix);
297 item.mModelViewMatrix = nodeModelViewMatrix;
299 partialRenderingCacheInfo.matrix = item.mModelViewMatrix;
300 partialRenderingCacheInfo.size = item.mSize;
301 partialRenderingCacheInfo.updatedSize = item.mUpdateSize;
303 item.mIsUpdated = partialRenderingData.IsUpdated() || item.mIsUpdated;
305 partialRenderingData.mRendered = true;
307 partialRenderingData.SwapBuffers();
311 // Mark as not rendered
312 auto& partialRenderingData = node->GetPartialRenderingData();
313 partialRenderingData.mRendered = false;
316 node->SetCulled(updateBufferIndex, false);
320 // Mark as not rendered
321 auto& partialRenderingData = node->GetPartialRenderingData();
322 partialRenderingData.mRendered = false;
324 node->SetCulled(updateBufferIndex, true);
329 * Add all renderers to the list
330 * @param updateBufferIndex to read the model matrix from
331 * @param renderList to add the items to
332 * @param renderers to render
333 * NodeRendererContainer Node-Renderer pairs
334 * @param viewMatrix used to calculate modelview matrix for the items
335 * @param camera The camera used to render
336 * @param isLayer3d Whether we are processing a 3D layer or not
337 * @param cull Whether frustum culling is enabled or not
339 inline void AddRenderersToRenderList(BufferIndex updateBufferIndex,
340 RenderList& renderList,
341 RenderableContainer& renderers,
342 const Matrix& viewMatrix,
343 SceneGraph::Camera& camera,
346 const Viewport& viewport,
349 DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, "AddRenderersToRenderList()\n");
351 for(auto&& renderer : renderers)
353 AddRendererToRenderList(updateBufferIndex,
366 * Try to reuse cached RenderItems from the RenderList
367 * This avoids recalculating the model view matrices in case this part of the scene was static
368 * An example case is a toolbar layer that rarely changes or a popup on top of the rest of the stage
369 * @param layer that is being processed
370 * @param renderList that is cached from frame N-1
371 * @param renderables list of renderables
373 inline bool TryReuseCachedRenderers(Layer& layer,
374 RenderList& renderList,
375 RenderableContainer& renderables)
377 bool retValue = false;
378 uint32_t renderableCount = static_cast<uint32_t>(renderables.Size());
379 // Check that the cached list originates from this layer and that the counts match
380 if((renderList.GetSourceLayer() == &layer) &&
381 (renderList.GetCachedItemCount() == renderableCount))
383 // Check that all the same renderers are there. This gives us additional security in avoiding rendering the wrong things.
384 // Render list is sorted so at this stage renderers may be in different order.
385 // Therefore we check a combined sum of all renderer addresses.
386 size_t checkSumNew = 0;
387 size_t checkSumOld = 0;
388 for(uint32_t index = 0; index < renderableCount; ++index)
390 if(DALI_LIKELY(renderables[index].mRenderer))
392 const Render::Renderer& renderer = renderables[index].mRenderer->GetRenderer();
393 checkSumNew += reinterpret_cast<std::size_t>(&renderer);
395 if(DALI_LIKELY(renderList.GetItem(index).mRenderer))
397 checkSumOld += reinterpret_cast<std::size_t>(&renderList.GetRenderer(index));
400 if(checkSumNew == checkSumOld)
402 // tell list to reuse its existing items
403 renderList.ReuseCachedItems();
411 inline bool SetupRenderList(RenderableContainer& renderables,
413 RenderInstruction& instruction,
414 bool tryReuseRenderList,
415 RenderList** renderList)
417 *renderList = &(instruction.GetNextFreeRenderList(renderables.Size()));
418 (*renderList)->SetClipping(layer.IsClipping(), layer.GetClippingBox());
419 (*renderList)->SetSourceLayer(&layer);
421 // Try to reuse cached RenderItems from last time around.
422 return (tryReuseRenderList && TryReuseCachedRenderers(layer, **renderList, renderables));
425 } // Anonymous namespace.
427 RenderInstructionProcessor::RenderInstructionProcessor()
430 // Set up a container of comparators for fast run-time selection.
431 mSortComparitors.Reserve(3u);
433 mSortComparitors.PushBack(CompareItems);
434 mSortComparitors.PushBack(CompareItems3D);
435 mSortComparitors.PushBack(CompareItems3DWithClipping);
438 RenderInstructionProcessor::~RenderInstructionProcessor() = default;
440 inline void RenderInstructionProcessor::SortRenderItems(BufferIndex bufferIndex, RenderList& renderList, Layer& layer, bool respectClippingOrder)
442 const uint32_t renderableCount = static_cast<uint32_t>(renderList.Count());
443 // Reserve space if needed.
444 const uint32_t oldcapacity = static_cast<uint32_t>(mSortingHelper.size());
445 if(oldcapacity < renderableCount)
447 mSortingHelper.reserve(renderableCount);
448 // Add real objects (reserve does not construct objects).
449 mSortingHelper.insert(mSortingHelper.begin() + oldcapacity,
450 (renderableCount - oldcapacity),
451 RenderInstructionProcessor::SortAttributes());
455 // Clear extra elements from helper, does not decrease capability.
456 mSortingHelper.resize(renderableCount);
459 // Calculate the sorting value, once per item by calling the layers sort function.
460 // Using an if and two for-loops rather than if inside for as its better for branch prediction.
461 if(layer.UsesDefaultSortFunction())
463 for(uint32_t index = 0; index < renderableCount; ++index)
465 RenderItem& item = renderList.GetItem(index);
467 if(DALI_LIKELY(item.mRenderer))
469 item.mRenderer->SetSortAttributes(mSortingHelper[index]);
473 mSortingHelper[index].textureSet = item.mTextureSet;
475 // The default sorting function should get inlined here.
476 mSortingHelper[index].zValue = Internal::Layer::ZValue(item.mModelViewMatrix.GetTranslation3()) - static_cast<float>(item.mDepthIndex);
478 // Keep the renderitem pointer in the helper so we can quickly reorder items after sort.
479 mSortingHelper[index].renderItem = &item;
484 const Dali::Layer::SortFunctionType sortFunction = layer.GetSortFunction();
485 for(uint32_t index = 0; index < renderableCount; ++index)
487 RenderItem& item = renderList.GetItem(index);
489 if(DALI_LIKELY(item.mRenderer))
491 item.mRenderer->SetSortAttributes(mSortingHelper[index]);
495 mSortingHelper[index].textureSet = item.mTextureSet;
497 mSortingHelper[index].zValue = (*sortFunction)(item.mModelViewMatrix.GetTranslation3()) - static_cast<float>(item.mDepthIndex);
499 // Keep the RenderItem pointer in the helper so we can quickly reorder items after sort.
500 mSortingHelper[index].renderItem = &item;
504 // Here we determine which comparitor (of the 3) to use.
507 // 2 is LAYER_3D + Clipping
508 const unsigned int comparitorIndex = layer.GetBehavior() == Dali::Layer::LAYER_3D ? respectClippingOrder ? 2u : 1u : 0u;
510 std::stable_sort(mSortingHelper.begin(), mSortingHelper.end(), mSortComparitors[comparitorIndex]);
512 // Reorder / re-populate the RenderItems in the RenderList to correct order based on the sortinghelper.
513 DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, "Sorted Transparent List:\n");
514 RenderItemContainer::Iterator renderListIter = renderList.GetContainer().Begin();
515 for(uint32_t index = 0; index < renderableCount; ++index, ++renderListIter)
517 *renderListIter = mSortingHelper[index].renderItem;
518 DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, " sortedList[%d] = %p\n", index, mSortingHelper[index].renderItem->mRenderer);
522 void RenderInstructionProcessor::Prepare(BufferIndex updateBufferIndex,
523 SortedLayerPointers& sortedLayers,
524 RenderTask& renderTask,
526 bool hasClippingNodes,
527 RenderInstructionContainer& instructions)
529 // Retrieve the RenderInstruction buffer from the RenderInstructionContainer
530 // then populate with instructions.
531 RenderInstruction& instruction = renderTask.PrepareRenderInstruction(updateBufferIndex);
532 bool viewMatrixHasNotChanged = !renderTask.ViewMatrixUpdated();
533 bool isRenderListAdded = false;
534 bool isRootLayerDirty = false;
536 const Matrix& viewMatrix = renderTask.GetViewMatrix(updateBufferIndex);
537 SceneGraph::Camera& camera = renderTask.GetCamera();
540 bool viewportSet = renderTask.QueryViewport(updateBufferIndex, viewport);
542 const SortedLayersIter endIter = sortedLayers.end();
543 for(SortedLayersIter iter = sortedLayers.begin(); iter != endIter; ++iter)
545 Layer& layer = **iter;
546 const bool tryReuseRenderList(viewMatrixHasNotChanged && layer.CanReuseRenderers(&renderTask.GetCamera()));
547 const bool isLayer3D = layer.GetBehavior() == Dali::Layer::LAYER_3D;
548 RenderList* renderList = nullptr;
550 if(layer.IsRoot() && (layer.GetDirtyFlags() != NodePropertyFlags::NOTHING))
552 // 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
553 isRootLayerDirty = true;
556 if(!layer.colorRenderables.Empty())
558 RenderableContainer& renderables = layer.colorRenderables;
560 if(!SetupRenderList(renderables, layer, instruction, tryReuseRenderList, &renderList))
562 renderList->SetHasColorRenderItems(true);
563 AddRenderersToRenderList(updateBufferIndex,
573 // We only use the clipping version of the sort comparitor if any clipping nodes exist within the RenderList.
574 SortRenderItems(updateBufferIndex, *renderList, layer, hasClippingNodes);
577 isRenderListAdded = true;
580 if(!layer.overlayRenderables.Empty())
582 RenderableContainer& renderables = layer.overlayRenderables;
584 if(!SetupRenderList(renderables, layer, instruction, tryReuseRenderList, &renderList))
586 renderList->SetHasColorRenderItems(false);
587 AddRenderersToRenderList(updateBufferIndex,
597 // Clipping hierarchy is irrelevant when sorting overlay items, so we specify using the non-clipping version of the sort comparitor.
598 SortRenderItems(updateBufferIndex, *renderList, layer, false);
601 isRenderListAdded = true;
605 // Inform the render instruction that all renderers have been added and this frame is complete.
606 instruction.UpdateCompleted();
608 if(isRenderListAdded || instruction.mIsClearColorSet || isRootLayerDirty)
610 instructions.PushBack(updateBufferIndex, &instruction);
614 } // namespace SceneGraph
616 } // namespace Internal