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/common/matrix-utils.h>
24 #include <dali/internal/event/actors/layer-impl.h> // for the default sorting function
25 #include <dali/internal/render/common/render-instruction-container.h>
26 #include <dali/internal/render/common/render-instruction.h>
27 #include <dali/internal/render/common/render-item.h>
28 #include <dali/internal/render/common/render-tracker.h>
29 #include <dali/internal/render/renderers/render-renderer.h>
30 #include <dali/internal/render/shaders/render-shader.h>
31 #include <dali/internal/update/manager/sorted-layers.h>
32 #include <dali/internal/update/nodes/partial-rendering-data.h>
33 #include <dali/internal/update/nodes/scene-graph-layer.h>
34 #include <dali/internal/update/render-tasks/scene-graph-render-task.h>
35 #include <dali/internal/update/rendering/scene-graph-texture-set.h>
36 #include <dali/public-api/actors/layer.h>
40 #if defined(DEBUG_ENABLED)
41 Debug::Filter* gRenderListLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_LISTS");
54 * Function which compares render items by shader/textureSet/geometry
55 * @param[in] lhs Left hand side item
56 * @param[in] rhs Right hand side item
57 * @return True if left item is greater than right
59 inline bool PartialCompareItems(const RenderInstructionProcessor::SortAttributes& lhs,
60 const RenderInstructionProcessor::SortAttributes& rhs)
62 if(lhs.shader == rhs.shader)
64 if(lhs.textureSet == rhs.textureSet)
66 return lhs.geometry < rhs.geometry;
68 return lhs.textureSet < rhs.textureSet;
70 return lhs.shader < rhs.shader;
74 * Function which sorts render items by depth index then by instance
75 * ptrs of shader/textureSet/geometry.
76 * @param[in] lhs Left hand side item
77 * @param[in] rhs Right hand side item
78 * @return True if left item is greater than right
80 bool CompareItems(const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs)
82 // @todo Consider replacing all these sortAttributes with a single long int that
83 // encapsulates the same data (e.g. the middle-order bits of the ptrs).
84 if(lhs.renderItem->mDepthIndex == rhs.renderItem->mDepthIndex)
86 return PartialCompareItems(lhs, rhs);
88 return lhs.renderItem->mDepthIndex < rhs.renderItem->mDepthIndex;
92 * Function which sorts the render items by Z function, then
93 * by instance ptrs of shader / geometry / material.
94 * @param[in] lhs Left hand side item
95 * @param[in] rhs Right hand side item
96 * @return True if left item is greater than right
98 bool CompareItems3D(const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs)
100 const bool lhsIsOpaque = lhs.renderItem->mIsOpaque;
101 if(lhsIsOpaque == rhs.renderItem->mIsOpaque)
105 // If both RenderItems are opaque, sort using shader, then material then geometry.
106 return PartialCompareItems(lhs, rhs);
110 // If both RenderItems are transparent, sort using Z, then shader, then material, then geometry.
111 if(Equals(lhs.zValue, rhs.zValue))
113 return PartialCompareItems(lhs, rhs);
115 return lhs.zValue > rhs.zValue;
125 * Function which sorts render items by clipping hierarchy, then Z function and instance ptrs of shader / geometry / material.
126 * @param[in] lhs Left hand side item
127 * @param[in] rhs Right hand side item
128 * @return True if left item is greater than right
130 bool CompareItems3DWithClipping(const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs)
132 // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
133 if(lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier)
135 return CompareItems3D(lhs, rhs);
138 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
142 * Set the update area of the node
143 * @param[in] node The node of the renderer
144 * @param[in] isLayer3d Whether we are processing a 3D layer or not
145 * @param[in,out] nodeWorldMatrix The world matrix of the node
146 * @param[in,out] nodeSize The size of the node
147 * @param[in,out] nodeUpdateArea The update area of the node
149 * @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).
151 inline bool SetNodeUpdateArea(Node* node, bool isLayer3d, Matrix& nodeWorldMatrix, Vector3& nodeSize, Vector4& nodeUpdateArea)
153 node->GetWorldMatrixAndSize(nodeWorldMatrix, nodeSize);
155 if(node->GetUpdateAreaHint() == Vector4::ZERO)
157 // RenderItem::CalculateViewportSpaceAABB cannot cope with z transform
158 // I don't use item.mModelMatrix.GetTransformComponents() for z transform, would be too slow
159 if(!isLayer3d && nodeWorldMatrix.GetZAxis() == Vector3(0.0f, 0.0f, 1.0f))
161 nodeUpdateArea = Vector4(0.0f, 0.0f, nodeSize.width, nodeSize.height);
164 // Keep nodeUpdateArea as Vector4::ZERO, and return true.
169 nodeUpdateArea = node->GetUpdateAreaHint();
175 * Add a renderer to the list
176 * @param updateBufferIndex to read the model matrix from
177 * @param renderList to add the item to
178 * @param renderable Node-Renderer pair
179 * @param viewMatrix used to calculate modelview matrix for the item
180 * @param camera The camera used to render
181 * @param isLayer3d Whether we are processing a 3D layer or not
182 * @param viewportSet Whether the viewport is set or not
183 * @param viewport The viewport
184 * @param cull Whether frustum culling is enabled or not
186 inline void AddRendererToRenderList(BufferIndex updateBufferIndex,
187 RenderList& renderList,
188 Renderable& renderable,
189 const Matrix& viewMatrix,
190 const SceneGraph::Camera& camera,
193 const Viewport& viewport,
197 Node* node = renderable.mNode;
198 Matrix nodeWorldMatrix(false);
200 Vector4 nodeUpdateArea;
201 bool nodeUpdateAreaSet(false);
202 bool nodeUpdateAreaUseHint(false);
203 Matrix nodeModelViewMatrix(false);
204 bool nodeModelViewMatrixSet(false);
206 // Don't cull items which have render callback
207 bool hasRenderCallback = (renderable.mRenderer && renderable.mRenderer->GetRenderCallback());
209 if(cull && renderable.mRenderer && (hasRenderCallback || (!renderable.mRenderer->GetShader().HintEnabled(Dali::Shader::Hint::MODIFIES_GEOMETRY) && node->GetClippingMode() == ClippingMode::DISABLED)))
211 const Vector4& boundingSphere = node->GetBoundingSphere();
212 inside = (boundingSphere.w > Math::MACHINE_EPSILON_1000) &&
213 (camera.CheckSphereInFrustum(updateBufferIndex, Vector3(boundingSphere), boundingSphere.w));
215 if(inside && !isLayer3d && viewportSet)
217 nodeUpdateAreaUseHint = SetNodeUpdateArea(node, isLayer3d, nodeWorldMatrix, nodeSize, nodeUpdateArea);
218 nodeUpdateAreaSet = true;
220 const Vector3& scale = node->GetWorldScale(updateBufferIndex);
221 const Vector3& size = Vector3(nodeUpdateArea.z, nodeUpdateArea.w, 1.0f) * scale;
223 if(size.LengthSquared() > Math::MACHINE_EPSILON_1000)
225 MatrixUtils::Multiply(nodeModelViewMatrix, nodeWorldMatrix, viewMatrix);
226 nodeModelViewMatrixSet = true;
228 // Assume actors are at z=0, compute AABB in view space & test rect intersection
229 // against z=0 plane boundaries for frustum. (NOT viewport). This should take into account
230 // magnification due to FOV etc.
232 // TODO : Below logic might need to refactor it.
233 // If camera is Perspective, we need to calculate clipping box by FoV. Currently, we just believe default camera setup OrthographicSize well.
234 // - If then, It must use math calculate like tan(fov) internally. So, we might need calculate it only one times, and cache.
235 ClippingBox boundingBox = RenderItem::CalculateTransformSpaceAABB(nodeModelViewMatrix, Vector3(nodeUpdateArea.x, nodeUpdateArea.y, 0.0f), Vector3(nodeUpdateArea.z, nodeUpdateArea.w, 0.0f));
236 ClippingBox clippingBox = camera.GetOrthographicClippingBox(updateBufferIndex);
237 inside = clippingBox.Intersects(boundingBox);
241 * Note, the API Camera::CheckAABBInFrustum() can be used to test if a bounding box is (partially/fully) inside the view frustum.
247 bool skipRender(false);
248 bool isOpaque = true;
249 if(!hasRenderCallback)
251 Renderer::OpacityType opacityType = renderable.mRenderer ? renderable.mRenderer->GetOpacityType(updateBufferIndex, *node) : Renderer::OPAQUE;
253 // We can skip render when node is not clipping and transparent
254 skipRender = (opacityType == Renderer::TRANSPARENT && node->GetClippingMode() == ClippingMode::DISABLED);
256 isOpaque = (opacityType == Renderer::OPAQUE);
261 // Get the next free RenderItem.
262 RenderItem& item = renderList.GetNextFreeItem();
264 PartialRenderingData partialRenderingData;
266 partialRenderingData.node = node;
267 partialRenderingData.renderer = renderable.mRenderer;
268 partialRenderingData.color = node->GetWorldColor(updateBufferIndex);
269 partialRenderingData.depthIndex = node->GetDepthIndex();
270 partialRenderingData.isOpaque = isOpaque;
272 partialRenderingData.textureSet = nullptr;
273 if(DALI_LIKELY(renderable.mRenderer))
275 partialRenderingData.color.a *= renderable.mRenderer->GetOpacity(updateBufferIndex);
276 partialRenderingData.textureSet = renderable.mRenderer->GetTextureSet();
280 item.mIsOpaque = isOpaque;
281 item.mColor = node->GetColor(updateBufferIndex);
283 item.mDepthIndex = 0;
286 item.mDepthIndex = node->GetDepthIndex();
289 if(DALI_LIKELY(renderable.mRenderer))
291 item.mRenderer = &renderable.mRenderer->GetRenderer();
292 item.mTextureSet = renderable.mRenderer->GetTextureSet();
293 item.mDepthIndex += renderable.mRenderer->GetDepthIndex();
295 // Get whether collected map is up to date
296 item.mIsUpdated |= renderable.mRenderer->UniformMapUpdated();
300 item.mRenderer = nullptr;
303 item.mIsUpdated |= isLayer3d;
305 if(!nodeUpdateAreaSet)
307 nodeUpdateAreaUseHint = SetNodeUpdateArea(node, isLayer3d, nodeWorldMatrix, nodeSize, nodeUpdateArea);
310 item.mSize = nodeSize;
311 item.mUpdateArea = nodeUpdateArea;
312 item.mModelMatrix = nodeWorldMatrix;
314 // Apply transform informations if node doesn't have update size hint and use VisualRenderer.
315 if(!nodeUpdateAreaUseHint && renderable.mRenderer && renderable.mRenderer->GetVisualProperties())
317 Vector3 updateSize = renderable.mRenderer->CalculateVisualTransformedUpdateSize(updateBufferIndex, Vector3(item.mUpdateArea.z, item.mUpdateArea.w, 0.0f));
318 item.mUpdateArea.z = updateSize.x;
319 item.mUpdateArea.w = updateSize.y;
322 if(!nodeModelViewMatrixSet)
324 MatrixUtils::Multiply(nodeModelViewMatrix, nodeWorldMatrix, viewMatrix);
326 item.mModelViewMatrix = nodeModelViewMatrix;
328 partialRenderingData.matrix = item.mModelViewMatrix;
329 partialRenderingData.updatedPositionSize = item.mUpdateArea;
330 partialRenderingData.size = item.mSize;
332 auto& nodePartialRenderingData = node->GetPartialRenderingData();
333 item.mIsUpdated = nodePartialRenderingData.IsUpdated(partialRenderingData) || item.mIsUpdated;
335 nodePartialRenderingData.Update(partialRenderingData);
339 // Mark as not rendered
340 auto& nodePartialRenderingData = node->GetPartialRenderingData();
341 nodePartialRenderingData.mRendered = false;
344 node->SetCulled(updateBufferIndex, false);
348 // Mark as not rendered
349 auto& nodePartialRenderingData = node->GetPartialRenderingData();
350 nodePartialRenderingData.mRendered = false;
352 node->SetCulled(updateBufferIndex, true);
357 * Add all renderers to the list
358 * @param updateBufferIndex to read the model matrix from
359 * @param renderList to add the items to
360 * @param renderers to render
361 * NodeRendererContainer Node-Renderer pairs
362 * @param viewMatrix used to calculate modelview matrix for the items
363 * @param camera The camera used to render
364 * @param isLayer3d Whether we are processing a 3D layer or not
365 * @param cull Whether frustum culling is enabled or not
367 inline void AddRenderersToRenderList(BufferIndex updateBufferIndex,
368 RenderList& renderList,
369 RenderableContainer& renderers,
370 const Matrix& viewMatrix,
371 const SceneGraph::Camera& camera,
374 const Viewport& viewport,
377 DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, "AddRenderersToRenderList()\n");
379 for(auto&& renderer : renderers)
381 AddRendererToRenderList(updateBufferIndex,
394 * Try to reuse cached RenderItems from the RenderList
395 * This avoids recalculating the model view matrices in case this part of the scene was static
396 * An example case is a toolbar layer that rarely changes or a popup on top of the rest of the stage
397 * @param layer that is being processed
398 * @param renderList that is cached from frame N-1
399 * @param renderables list of renderables
401 inline bool TryReuseCachedRenderers(Layer& layer,
402 RenderList& renderList,
403 RenderableContainer& renderables)
405 bool retValue = false;
406 uint32_t renderableCount = static_cast<uint32_t>(renderables.Size());
407 // Check that the cached list originates from this layer and that the counts match
408 if((renderList.GetSourceLayer() == &layer) &&
409 (renderList.GetCachedItemCount() == renderableCount))
411 // Check that all the same renderers are there. This gives us additional security in avoiding rendering the wrong things.
412 // Render list is sorted so at this stage renderers may be in different order.
413 // Therefore we check a combined sum of all renderer addresses.
414 size_t checkSumNew = 0;
415 size_t checkSumOld = 0;
416 for(uint32_t index = 0; index < renderableCount; ++index)
418 if(DALI_LIKELY(renderables[index].mRenderer))
420 const Render::Renderer& renderer = renderables[index].mRenderer->GetRenderer();
421 checkSumNew += reinterpret_cast<std::size_t>(&renderer);
423 if(DALI_LIKELY(renderList.GetItem(index).mRenderer))
425 checkSumOld += reinterpret_cast<std::size_t>(&renderList.GetRenderer(index));
428 if(checkSumNew == checkSumOld)
430 // tell list to reuse its existing items
431 renderList.ReuseCachedItems();
439 inline bool SetupRenderList(RenderableContainer& renderables,
441 RenderInstruction& instruction,
442 bool tryReuseRenderList,
443 RenderList** renderList)
445 *renderList = &(instruction.GetNextFreeRenderList(renderables.Size()));
446 (*renderList)->SetClipping(layer.IsClipping(), layer.GetClippingBox());
447 (*renderList)->SetSourceLayer(&layer);
449 // Try to reuse cached RenderItems from last time around.
450 return (tryReuseRenderList && TryReuseCachedRenderers(layer, **renderList, renderables));
453 } // Anonymous namespace.
455 RenderInstructionProcessor::RenderInstructionProcessor()
458 // Set up a container of comparators for fast run-time selection.
459 mSortComparitors.Reserve(3u);
461 mSortComparitors.PushBack(CompareItems);
462 mSortComparitors.PushBack(CompareItems3D);
463 mSortComparitors.PushBack(CompareItems3DWithClipping);
466 RenderInstructionProcessor::~RenderInstructionProcessor() = default;
468 inline void RenderInstructionProcessor::SortRenderItems(BufferIndex bufferIndex, RenderList& renderList, Layer& layer, bool respectClippingOrder, bool isOrthographicCamera)
470 const uint32_t renderableCount = static_cast<uint32_t>(renderList.Count());
471 // Reserve space if needed.
472 const uint32_t oldcapacity = static_cast<uint32_t>(mSortingHelper.size());
473 if(oldcapacity < renderableCount)
475 mSortingHelper.reserve(renderableCount);
476 // Add real objects (reserve does not construct objects).
477 mSortingHelper.insert(mSortingHelper.begin() + oldcapacity,
478 (renderableCount - oldcapacity),
479 RenderInstructionProcessor::SortAttributes());
483 // Clear extra elements from helper, does not decrease capability.
484 mSortingHelper.resize(renderableCount);
487 // Calculate the sorting value, once per item by calling the layers sort function.
488 // Using an if and two for-loops rather than if inside for as its better for branch prediction.
490 // List of zValue calculating functions.
491 const Dali::Layer::SortFunctionType zValueFunctionFromVector3[] = {
492 [](const Vector3& position)
493 { return position.z; },
494 [](const Vector3& position)
495 { return position.LengthSquared(); },
496 layer.GetSortFunction(),
499 // Determine whether we need to use zValue as Euclidean distance or translatoin's z value.
500 // If layer is LAYER_UI or camera is OrthographicProjection mode, we don't need to calculate
501 // renderItem's distance from camera.
503 // Here we determine which zValue SortFunctionType (of the 3) to use.
504 // 0 is position z value : Default LAYER_UI or Orthographic camera
505 // 1 is distance square value : Default LAYER_3D and Perspective camera
506 // 2 is user defined function.
507 const int zValueFunctionIndex = layer.UsesDefaultSortFunction() ? ((layer.GetBehavior() == Dali::Layer::LAYER_UI || isOrthographicCamera) ? 0 : 1) : 2;
509 for(uint32_t index = 0; index < renderableCount; ++index)
511 RenderItem& item = renderList.GetItem(index);
513 if(DALI_LIKELY(item.mRenderer))
515 item.mRenderer->SetSortAttributes(mSortingHelper[index]);
519 mSortingHelper[index].textureSet = item.mTextureSet;
521 mSortingHelper[index].zValue = zValueFunctionFromVector3[zValueFunctionIndex](item.mModelViewMatrix.GetTranslation3()) - static_cast<float>(item.mDepthIndex);
523 // Keep the renderitem pointer in the helper so we can quickly reorder items after sort.
524 mSortingHelper[index].renderItem = &item;
527 // Here we determine which comparitor (of the 3) to use.
530 // 2 is LAYER_3D + Clipping
531 const unsigned int comparitorIndex = layer.GetBehavior() == Dali::Layer::LAYER_3D ? respectClippingOrder ? 2u : 1u : 0u;
533 std::stable_sort(mSortingHelper.begin(), mSortingHelper.end(), mSortComparitors[comparitorIndex]);
535 // Reorder / re-populate the RenderItems in the RenderList to correct order based on the sortinghelper.
536 DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, "Sorted Transparent List:\n");
537 RenderItemContainer::Iterator renderListIter = renderList.GetContainer().Begin();
538 for(uint32_t index = 0; index < renderableCount; ++index, ++renderListIter)
540 *renderListIter = mSortingHelper[index].renderItem;
541 DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, " sortedList[%d] = %p\n", index, mSortingHelper[index].renderItem->mRenderer);
545 void RenderInstructionProcessor::Prepare(BufferIndex updateBufferIndex,
546 SortedLayerPointers& sortedLayers,
547 RenderTask& renderTask,
549 bool hasClippingNodes,
550 RenderInstructionContainer& instructions)
552 // Retrieve the RenderInstruction buffer from the RenderInstructionContainer
553 // then populate with instructions.
554 RenderInstruction& instruction = renderTask.PrepareRenderInstruction(updateBufferIndex);
555 bool viewMatrixHasNotChanged = !renderTask.ViewMatrixUpdated();
556 bool isRenderListAdded = false;
557 bool isRootLayerDirty = false;
559 const Matrix& viewMatrix = renderTask.GetViewMatrix(updateBufferIndex);
560 const SceneGraph::Camera& camera = renderTask.GetCamera();
561 const bool isOrthographicCamera = camera.mProjectionMode == Dali::Camera::ProjectionMode::ORTHOGRAPHIC_PROJECTION;
564 bool viewportSet = renderTask.QueryViewport(updateBufferIndex, viewport);
566 const SortedLayersIter endIter = sortedLayers.end();
567 for(SortedLayersIter iter = sortedLayers.begin(); iter != endIter; ++iter)
569 Layer& layer = **iter;
570 const bool tryReuseRenderList(viewMatrixHasNotChanged && layer.CanReuseRenderers(&camera));
571 const bool isLayer3D = layer.GetBehavior() == Dali::Layer::LAYER_3D;
572 RenderList* renderList = nullptr;
574 if(layer.IsRoot() && (layer.GetDirtyFlags() != NodePropertyFlags::NOTHING))
576 // 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
577 isRootLayerDirty = true;
580 if(!layer.colorRenderables.Empty())
582 RenderableContainer& renderables = layer.colorRenderables;
584 if(!SetupRenderList(renderables, layer, instruction, tryReuseRenderList, &renderList))
586 renderList->SetHasColorRenderItems(true);
587 AddRenderersToRenderList(updateBufferIndex,
597 // We only use the clipping version of the sort comparitor if any clipping nodes exist within the RenderList.
598 SortRenderItems(updateBufferIndex, *renderList, layer, hasClippingNodes, isOrthographicCamera);
601 isRenderListAdded = true;
604 if(!layer.overlayRenderables.Empty())
606 RenderableContainer& renderables = layer.overlayRenderables;
608 if(!SetupRenderList(renderables, layer, instruction, tryReuseRenderList, &renderList))
610 renderList->SetHasColorRenderItems(false);
611 AddRenderersToRenderList(updateBufferIndex,
621 // Clipping hierarchy is irrelevant when sorting overlay items, so we specify using the non-clipping version of the sort comparitor.
622 SortRenderItems(updateBufferIndex, *renderList, layer, false, isOrthographicCamera);
625 isRenderListAdded = true;
629 // Inform the render instruction that all renderers have been added and this frame is complete.
630 instruction.UpdateCompleted();
632 if(isRenderListAdded || instruction.mIsClearColorSet || isRootLayerDirty)
634 instructions.PushBack(updateBufferIndex, &instruction);
638 } // namespace SceneGraph
640 } // namespace Internal