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 area 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] nodeUpdateArea The update area of the node
147 * @return True if node use it's own UpdateAreaHint, or z transform occured. False if we use nodeUpdateArea equal with Vector4(0, 0, nodeSize.width, nodeSize.height).
149 inline bool SetNodeUpdateArea(Node* node, bool isLayer3d, Matrix& nodeWorldMatrix, Vector3& nodeSize, Vector4& nodeUpdateArea)
151 node->GetWorldMatrixAndSize(nodeWorldMatrix, nodeSize);
153 if(node->GetUpdateAreaHint() == Vector4::ZERO)
155 // RenderItem::CalculateViewportSpaceAABB cannot cope with z transform
156 // I don't use item.mModelMatrix.GetTransformComponents() for z transform, would be too slow
157 if(!isLayer3d && nodeWorldMatrix.GetZAxis() == Vector3(0.0f, 0.0f, 1.0f))
159 nodeUpdateArea = Vector4(0.0f, 0.0f, nodeSize.width, nodeSize.height);
162 // Keep nodeUpdateArea as Vector4::ZERO, and return true.
167 nodeUpdateArea = node->GetUpdateAreaHint();
173 * Add a renderer to the list
174 * @param updateBufferIndex to read the model matrix from
175 * @param renderList to add the item to
176 * @param renderable Node-Renderer pair
177 * @param viewMatrix used to calculate modelview matrix for the item
178 * @param camera The camera used to render
179 * @param isLayer3d Whether we are processing a 3D layer or not
180 * @param viewportSet Whether the viewport is set or not
181 * @param viewport The viewport
182 * @param cull Whether frustum culling is enabled or not
184 inline void AddRendererToRenderList(BufferIndex updateBufferIndex,
185 RenderList& renderList,
186 Renderable& renderable,
187 const Matrix& viewMatrix,
188 const SceneGraph::Camera& camera,
191 const Viewport& viewport,
195 Node* node = renderable.mNode;
196 Matrix nodeWorldMatrix(false);
198 Vector4 nodeUpdateArea;
199 bool nodeUpdateAreaSet(false);
200 bool nodeUpdateAreaUseHint(false);
201 Matrix nodeModelViewMatrix(false);
202 bool nodeModelViewMatrixSet(false);
204 // Don't cull items which have render callback
205 bool hasRenderCallback = (renderable.mRenderer && renderable.mRenderer->GetRenderCallback());
207 if(cull && renderable.mRenderer && (hasRenderCallback || (!renderable.mRenderer->GetShader().HintEnabled(Dali::Shader::Hint::MODIFIES_GEOMETRY) && node->GetClippingMode() == ClippingMode::DISABLED)))
209 const Vector4& boundingSphere = node->GetBoundingSphere();
210 inside = (boundingSphere.w > Math::MACHINE_EPSILON_1000) &&
211 (camera.CheckSphereInFrustum(updateBufferIndex, Vector3(boundingSphere), boundingSphere.w));
213 if(inside && !isLayer3d && viewportSet)
215 nodeUpdateAreaUseHint = SetNodeUpdateArea(node, isLayer3d, nodeWorldMatrix, nodeSize, nodeUpdateArea);
216 nodeUpdateAreaSet = true;
218 const Vector3& scale = node->GetWorldScale(updateBufferIndex);
219 const Vector3& size = Vector3(nodeUpdateArea.z, nodeUpdateArea.w, 1.0f) * scale;
221 if(size.LengthSquared() > Math::MACHINE_EPSILON_1000)
223 Matrix::Multiply(nodeModelViewMatrix, nodeWorldMatrix, viewMatrix);
224 nodeModelViewMatrixSet = true;
226 // Assume actors are at z=0, compute AABB in view space & test rect intersection
227 // against z=0 plane boundaries for frustum. (NOT viewport). This should take into account
228 // magnification due to FOV etc.
229 ClippingBox boundingBox = RenderItem::CalculateTransformSpaceAABB(nodeModelViewMatrix, Vector3(nodeUpdateArea.x, nodeUpdateArea.y, 0.0f), Vector3(nodeUpdateArea.z, nodeUpdateArea.w, 0.0f));
230 ClippingBox clippingBox(camera.mLeftClippingPlane, camera.mBottomClippingPlane, camera.mRightClippingPlane - camera.mLeftClippingPlane, fabsf(camera.mBottomClippingPlane - camera.mTopClippingPlane));
231 inside = clippingBox.Intersects(boundingBox);
235 * Note, the API Camera::CheckAABBInFrustum() can be used to test if a bounding box is (partially/fully) inside the view frustum.
241 bool skipRender(false);
242 bool isOpaque = true;
243 if(!hasRenderCallback)
245 Renderer::OpacityType opacityType = renderable.mRenderer ? renderable.mRenderer->GetOpacityType(updateBufferIndex, *node) : Renderer::OPAQUE;
247 // We can skip render when node is not clipping and transparent
248 skipRender = (opacityType == Renderer::TRANSPARENT && node->GetClippingMode() == ClippingMode::DISABLED);
250 isOpaque = (opacityType == Renderer::OPAQUE);
255 // Get the next free RenderItem.
256 RenderItem& item = renderList.GetNextFreeItem();
259 auto& partialRenderingData = node->GetPartialRenderingData();
261 auto& partialRenderingCacheInfo = node->GetPartialRenderingData().GetCurrentCacheInfo();
263 partialRenderingCacheInfo.node = node;
264 partialRenderingCacheInfo.isOpaque = isOpaque;
265 partialRenderingCacheInfo.renderer = renderable.mRenderer;
266 partialRenderingCacheInfo.color = node->GetWorldColor(updateBufferIndex);
267 partialRenderingCacheInfo.depthIndex = node->GetDepthIndex();
269 if(DALI_LIKELY(renderable.mRenderer))
271 partialRenderingCacheInfo.color.a *= renderable.mRenderer->GetOpacity(updateBufferIndex);
272 partialRenderingCacheInfo.textureSet = renderable.mRenderer->GetTextureSet();
276 item.mIsOpaque = isOpaque;
277 item.mColor = node->GetColor(updateBufferIndex);
279 item.mDepthIndex = 0;
282 item.mDepthIndex = node->GetDepthIndex();
285 if(DALI_LIKELY(renderable.mRenderer))
287 item.mRenderer = &renderable.mRenderer->GetRenderer();
288 item.mTextureSet = renderable.mRenderer->GetTextureSet();
289 item.mDepthIndex += renderable.mRenderer->GetDepthIndex();
291 // Get whether collected map is up to date
292 item.mIsUpdated |= renderable.mRenderer->UniformMapUpdated();
296 item.mRenderer = nullptr;
299 item.mIsUpdated |= isLayer3d;
301 if(!nodeUpdateAreaSet)
303 nodeUpdateAreaUseHint = SetNodeUpdateArea(node, isLayer3d, nodeWorldMatrix, nodeSize, nodeUpdateArea);
306 item.mSize = nodeSize;
307 item.mUpdateArea = nodeUpdateArea;
308 item.mModelMatrix = nodeWorldMatrix;
310 // Apply transform informations if node doesn't have update size hint and use VisualRenderer.
311 if(!nodeUpdateAreaUseHint && renderable.mRenderer && renderable.mRenderer->GetVisualProperties())
313 Vector3 updateSize = renderable.mRenderer->CalculateVisualTransformedUpdateSize(updateBufferIndex, Vector3(item.mUpdateArea.z, item.mUpdateArea.w, 0.0f));
314 item.mUpdateArea.z = updateSize.x;
315 item.mUpdateArea.w = updateSize.y;
318 if(!nodeModelViewMatrixSet)
320 Matrix::Multiply(nodeModelViewMatrix, nodeWorldMatrix, viewMatrix);
322 item.mModelViewMatrix = nodeModelViewMatrix;
324 partialRenderingCacheInfo.matrix = item.mModelViewMatrix;
325 partialRenderingCacheInfo.size = item.mSize;
326 partialRenderingCacheInfo.updatedPositionSize = item.mUpdateArea;
328 item.mIsUpdated = partialRenderingData.IsUpdated() || item.mIsUpdated;
330 partialRenderingData.mRendered = true;
332 partialRenderingData.SwapBuffers();
336 // Mark as not rendered
337 auto& partialRenderingData = node->GetPartialRenderingData();
338 partialRenderingData.mRendered = false;
341 node->SetCulled(updateBufferIndex, false);
345 // Mark as not rendered
346 auto& partialRenderingData = node->GetPartialRenderingData();
347 partialRenderingData.mRendered = false;
349 node->SetCulled(updateBufferIndex, true);
354 * Add all renderers to the list
355 * @param updateBufferIndex to read the model matrix from
356 * @param renderList to add the items to
357 * @param renderers to render
358 * NodeRendererContainer Node-Renderer pairs
359 * @param viewMatrix used to calculate modelview matrix for the items
360 * @param camera The camera used to render
361 * @param isLayer3d Whether we are processing a 3D layer or not
362 * @param cull Whether frustum culling is enabled or not
364 inline void AddRenderersToRenderList(BufferIndex updateBufferIndex,
365 RenderList& renderList,
366 RenderableContainer& renderers,
367 const Matrix& viewMatrix,
368 const SceneGraph::Camera& camera,
371 const Viewport& viewport,
374 DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, "AddRenderersToRenderList()\n");
376 for(auto&& renderer : renderers)
378 AddRendererToRenderList(updateBufferIndex,
391 * Try to reuse cached RenderItems from the RenderList
392 * This avoids recalculating the model view matrices in case this part of the scene was static
393 * An example case is a toolbar layer that rarely changes or a popup on top of the rest of the stage
394 * @param layer that is being processed
395 * @param renderList that is cached from frame N-1
396 * @param renderables list of renderables
398 inline bool TryReuseCachedRenderers(Layer& layer,
399 RenderList& renderList,
400 RenderableContainer& renderables)
402 bool retValue = false;
403 uint32_t renderableCount = static_cast<uint32_t>(renderables.Size());
404 // Check that the cached list originates from this layer and that the counts match
405 if((renderList.GetSourceLayer() == &layer) &&
406 (renderList.GetCachedItemCount() == renderableCount))
408 // Check that all the same renderers are there. This gives us additional security in avoiding rendering the wrong things.
409 // Render list is sorted so at this stage renderers may be in different order.
410 // Therefore we check a combined sum of all renderer addresses.
411 size_t checkSumNew = 0;
412 size_t checkSumOld = 0;
413 for(uint32_t index = 0; index < renderableCount; ++index)
415 if(DALI_LIKELY(renderables[index].mRenderer))
417 const Render::Renderer& renderer = renderables[index].mRenderer->GetRenderer();
418 checkSumNew += reinterpret_cast<std::size_t>(&renderer);
420 if(DALI_LIKELY(renderList.GetItem(index).mRenderer))
422 checkSumOld += reinterpret_cast<std::size_t>(&renderList.GetRenderer(index));
425 if(checkSumNew == checkSumOld)
427 // tell list to reuse its existing items
428 renderList.ReuseCachedItems();
436 inline bool SetupRenderList(RenderableContainer& renderables,
438 RenderInstruction& instruction,
439 bool tryReuseRenderList,
440 RenderList** renderList)
442 *renderList = &(instruction.GetNextFreeRenderList(renderables.Size()));
443 (*renderList)->SetClipping(layer.IsClipping(), layer.GetClippingBox());
444 (*renderList)->SetSourceLayer(&layer);
446 // Try to reuse cached RenderItems from last time around.
447 return (tryReuseRenderList && TryReuseCachedRenderers(layer, **renderList, renderables));
450 } // Anonymous namespace.
452 RenderInstructionProcessor::RenderInstructionProcessor()
455 // Set up a container of comparators for fast run-time selection.
456 mSortComparitors.Reserve(3u);
458 mSortComparitors.PushBack(CompareItems);
459 mSortComparitors.PushBack(CompareItems3D);
460 mSortComparitors.PushBack(CompareItems3DWithClipping);
463 RenderInstructionProcessor::~RenderInstructionProcessor() = default;
465 inline void RenderInstructionProcessor::SortRenderItems(BufferIndex bufferIndex, RenderList& renderList, Layer& layer, bool respectClippingOrder)
467 const uint32_t renderableCount = static_cast<uint32_t>(renderList.Count());
468 // Reserve space if needed.
469 const uint32_t oldcapacity = static_cast<uint32_t>(mSortingHelper.size());
470 if(oldcapacity < renderableCount)
472 mSortingHelper.reserve(renderableCount);
473 // Add real objects (reserve does not construct objects).
474 mSortingHelper.insert(mSortingHelper.begin() + oldcapacity,
475 (renderableCount - oldcapacity),
476 RenderInstructionProcessor::SortAttributes());
480 // Clear extra elements from helper, does not decrease capability.
481 mSortingHelper.resize(renderableCount);
484 // Calculate the sorting value, once per item by calling the layers sort function.
485 // Using an if and two for-loops rather than if inside for as its better for branch prediction.
486 if(layer.UsesDefaultSortFunction())
488 for(uint32_t index = 0; index < renderableCount; ++index)
490 RenderItem& item = renderList.GetItem(index);
492 if(DALI_LIKELY(item.mRenderer))
494 item.mRenderer->SetSortAttributes(mSortingHelper[index]);
498 mSortingHelper[index].textureSet = item.mTextureSet;
500 // The default sorting function should get inlined here.
501 mSortingHelper[index].zValue = Internal::Layer::ZValue(item.mModelViewMatrix.GetTranslation3()) - static_cast<float>(item.mDepthIndex);
503 // Keep the renderitem pointer in the helper so we can quickly reorder items after sort.
504 mSortingHelper[index].renderItem = &item;
509 const Dali::Layer::SortFunctionType sortFunction = layer.GetSortFunction();
510 for(uint32_t index = 0; index < renderableCount; ++index)
512 RenderItem& item = renderList.GetItem(index);
514 if(DALI_LIKELY(item.mRenderer))
516 item.mRenderer->SetSortAttributes(mSortingHelper[index]);
520 mSortingHelper[index].textureSet = item.mTextureSet;
522 mSortingHelper[index].zValue = (*sortFunction)(item.mModelViewMatrix.GetTranslation3()) - static_cast<float>(item.mDepthIndex);
524 // Keep the RenderItem pointer in the helper so we can quickly reorder items after sort.
525 mSortingHelper[index].renderItem = &item;
529 // Here we determine which comparitor (of the 3) to use.
532 // 2 is LAYER_3D + Clipping
533 const unsigned int comparitorIndex = layer.GetBehavior() == Dali::Layer::LAYER_3D ? respectClippingOrder ? 2u : 1u : 0u;
535 std::stable_sort(mSortingHelper.begin(), mSortingHelper.end(), mSortComparitors[comparitorIndex]);
537 // Reorder / re-populate the RenderItems in the RenderList to correct order based on the sortinghelper.
538 DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, "Sorted Transparent List:\n");
539 RenderItemContainer::Iterator renderListIter = renderList.GetContainer().Begin();
540 for(uint32_t index = 0; index < renderableCount; ++index, ++renderListIter)
542 *renderListIter = mSortingHelper[index].renderItem;
543 DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, " sortedList[%d] = %p\n", index, mSortingHelper[index].renderItem->mRenderer);
547 void RenderInstructionProcessor::Prepare(BufferIndex updateBufferIndex,
548 SortedLayerPointers& sortedLayers,
549 RenderTask& renderTask,
551 bool hasClippingNodes,
552 RenderInstructionContainer& instructions)
554 // Retrieve the RenderInstruction buffer from the RenderInstructionContainer
555 // then populate with instructions.
556 RenderInstruction& instruction = renderTask.PrepareRenderInstruction(updateBufferIndex);
557 bool viewMatrixHasNotChanged = !renderTask.ViewMatrixUpdated();
558 bool isRenderListAdded = false;
559 bool isRootLayerDirty = false;
561 const Matrix& viewMatrix = renderTask.GetViewMatrix(updateBufferIndex);
562 const SceneGraph::Camera& camera = renderTask.GetCamera();
565 bool viewportSet = renderTask.QueryViewport(updateBufferIndex, viewport);
567 const SortedLayersIter endIter = sortedLayers.end();
568 for(SortedLayersIter iter = sortedLayers.begin(); iter != endIter; ++iter)
570 Layer& layer = **iter;
571 const bool tryReuseRenderList(viewMatrixHasNotChanged && layer.CanReuseRenderers(&camera));
572 const bool isLayer3D = layer.GetBehavior() == Dali::Layer::LAYER_3D;
573 RenderList* renderList = nullptr;
575 if(layer.IsRoot() && (layer.GetDirtyFlags() != NodePropertyFlags::NOTHING))
577 // 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
578 isRootLayerDirty = true;
581 if(!layer.colorRenderables.Empty())
583 RenderableContainer& renderables = layer.colorRenderables;
585 if(!SetupRenderList(renderables, layer, instruction, tryReuseRenderList, &renderList))
587 renderList->SetHasColorRenderItems(true);
588 AddRenderersToRenderList(updateBufferIndex,
598 // We only use the clipping version of the sort comparitor if any clipping nodes exist within the RenderList.
599 SortRenderItems(updateBufferIndex, *renderList, layer, hasClippingNodes);
602 isRenderListAdded = true;
605 if(!layer.overlayRenderables.Empty())
607 RenderableContainer& renderables = layer.overlayRenderables;
609 if(!SetupRenderList(renderables, layer, instruction, tryReuseRenderList, &renderList))
611 renderList->SetHasColorRenderItems(false);
612 AddRenderersToRenderList(updateBufferIndex,
622 // Clipping hierarchy is irrelevant when sorting overlay items, so we specify using the non-clipping version of the sort comparitor.
623 SortRenderItems(updateBufferIndex, *renderList, layer, false);
626 isRenderListAdded = true;
630 // Inform the render instruction that all renderers have been added and this frame is complete.
631 instruction.UpdateCompleted();
633 if(isRenderListAdded || instruction.mIsClearColorSet || isRootLayerDirty)
635 instructions.PushBack(updateBufferIndex, &instruction);
639 } // namespace SceneGraph
641 } // namespace Internal