2 * Copyright (c) 2021 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 * Add a renderer to the list
141 * @param updateBufferIndex to read the model matrix from
142 * @param renderList to add the item to
143 * @param renderable Node-Renderer pair
144 * @param viewMatrix used to calculate modelview matrix for the item
145 * @param camera The camera used to render
146 * @param isLayer3d Whether we are processing a 3D layer or not
147 * @param cull Whether frustum culling is enabled or not
149 inline void AddRendererToRenderList(BufferIndex updateBufferIndex,
150 RenderList& renderList,
151 Renderable& renderable,
152 const Matrix& viewMatrix,
153 SceneGraph::Camera& camera,
158 Node* node = renderable.mNode;
160 if(cull && renderable.mRenderer && !renderable.mRenderer->GetShader().HintEnabled(Dali::Shader::Hint::MODIFIES_GEOMETRY))
162 const Vector4& boundingSphere = node->GetBoundingSphere();
163 inside = (boundingSphere.w > Math::MACHINE_EPSILON_1000) &&
164 (camera.CheckSphereInFrustum(updateBufferIndex, Vector3(boundingSphere), boundingSphere.w));
169 Renderer::OpacityType opacityType = renderable.mRenderer ? renderable.mRenderer->GetOpacityType(updateBufferIndex, *renderable.mNode) : Renderer::OPAQUE;
170 if(opacityType != Renderer::TRANSPARENT || node->GetClippingMode() != ClippingMode::DISABLED)
172 // Get the next free RenderItem.
173 RenderItem& item = renderList.GetNextFreeItem();
176 auto& partialRenderingData = node->GetPartialRenderingData();
178 auto& partialRenderingCacheInfo = node->GetPartialRenderingData().GetCurrentCacheInfo();
180 partialRenderingCacheInfo.node = node;
181 partialRenderingCacheInfo.isOpaque = (opacityType == Renderer::OPAQUE);
182 partialRenderingCacheInfo.renderer = renderable.mRenderer;
183 partialRenderingCacheInfo.color = renderable.mNode->GetColor(updateBufferIndex);
184 partialRenderingCacheInfo.depthIndex = renderable.mNode->GetDepthIndex();
186 if(renderable.mRenderer)
188 partialRenderingCacheInfo.textureSet = renderable.mRenderer->GetTextures();
191 item.mNode = renderable.mNode;
192 item.mIsOpaque = (opacityType == Renderer::OPAQUE);
193 item.mColor = renderable.mNode->GetColor(updateBufferIndex);
195 item.mDepthIndex = 0;
198 item.mDepthIndex = renderable.mNode->GetDepthIndex();
201 if(DALI_LIKELY(renderable.mRenderer))
203 item.mRenderer = &renderable.mRenderer->GetRenderer();
204 item.mTextureSet = renderable.mRenderer->GetTextures();
205 item.mDepthIndex += renderable.mRenderer->GetDepthIndex();
209 item.mRenderer = nullptr;
212 item.mIsUpdated |= isLayer3d;
214 // Save ModelView matrix onto the item.
215 node->GetWorldMatrixAndSize(item.mModelMatrix, item.mSize);
216 Matrix::Multiply(item.mModelViewMatrix, item.mModelMatrix, viewMatrix);
218 partialRenderingCacheInfo.matrix = item.mModelViewMatrix;
219 partialRenderingCacheInfo.size = item.mSize;
221 if(renderable.mNode->GetUpdateSizeHint() == Vector3::ZERO)
223 // RenderItem::CalculateViewportSpaceAABB cannot cope with z transform
224 // I don't use item.mModelMatrix.GetTransformComponents() for z transform, would be to slow
225 if(!isLayer3d && item.mModelMatrix.GetZAxis() == Vector3(0.0f, 0.0f, 1.0f))
227 item.mUpdateSize = item.mSize;
232 item.mUpdateSize = renderable.mNode->GetUpdateSizeHint();
235 partialRenderingCacheInfo.updatedSize = item.mUpdateSize;
237 item.mIsUpdated = partialRenderingData.IsUpdated() || item.mIsUpdated;
238 partialRenderingData.SwapBuffers();
240 node->SetCulled(updateBufferIndex, false);
244 node->SetCulled(updateBufferIndex, true);
249 * Add all renderers to the list
250 * @param updateBufferIndex to read the model matrix from
251 * @param renderList to add the items to
252 * @param renderers to render
253 * NodeRendererContainer Node-Renderer pairs
254 * @param viewMatrix used to calculate modelview matrix for the items
255 * @param camera The camera used to render
256 * @param isLayer3d Whether we are processing a 3D layer or not
257 * @param cull Whether frustum culling is enabled or not
259 inline void AddRenderersToRenderList(BufferIndex updateBufferIndex,
260 RenderList& renderList,
261 RenderableContainer& renderers,
262 const Matrix& viewMatrix,
263 SceneGraph::Camera& camera,
267 DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, "AddRenderersToRenderList()\n");
269 for(auto&& renderer : renderers)
271 AddRendererToRenderList(updateBufferIndex,
282 * Try to reuse cached RenderItems from the RenderList
283 * This avoids recalculating the model view matrices in case this part of the scene was static
284 * An example case is a toolbar layer that rarely changes or a popup on top of the rest of the stage
285 * @param layer that is being processed
286 * @param renderList that is cached from frame N-1
287 * @param renderables list of renderables
289 inline bool TryReuseCachedRenderers(Layer& layer,
290 RenderList& renderList,
291 RenderableContainer& renderables)
293 bool retValue = false;
294 uint32_t renderableCount = static_cast<uint32_t>(renderables.Size());
295 // Check that the cached list originates from this layer and that the counts match
296 if((renderList.GetSourceLayer() == &layer) &&
297 (renderList.GetCachedItemCount() == renderableCount))
299 // Check that all the same renderers are there. This gives us additional security in avoiding rendering the wrong things.
300 // Render list is sorted so at this stage renderers may be in different order.
301 // Therefore we check a combined sum of all renderer addresses.
302 size_t checkSumNew = 0;
303 size_t checkSumOld = 0;
304 for(uint32_t index = 0; index < renderableCount; ++index)
306 const Render::Renderer& renderer = renderables[index].mRenderer->GetRenderer();
307 checkSumNew += reinterpret_cast<std::size_t>(&renderer);
308 checkSumOld += reinterpret_cast<std::size_t>(&renderList.GetRenderer(index));
310 if(checkSumNew == checkSumOld)
312 // tell list to reuse its existing items
313 renderList.ReuseCachedItems();
321 inline bool SetupRenderList(RenderableContainer& renderables,
323 RenderInstruction& instruction,
324 bool tryReuseRenderList,
325 RenderList** renderList)
327 *renderList = &(instruction.GetNextFreeRenderList(renderables.Size()));
328 (*renderList)->SetClipping(layer.IsClipping(), layer.GetClippingBox());
329 (*renderList)->SetSourceLayer(&layer);
331 // Try to reuse cached RenderItems from last time around.
332 return (tryReuseRenderList && TryReuseCachedRenderers(layer, **renderList, renderables));
335 } // Anonymous namespace.
337 RenderInstructionProcessor::RenderInstructionProcessor()
340 // Set up a container of comparators for fast run-time selection.
341 mSortComparitors.Reserve(3u);
343 mSortComparitors.PushBack(CompareItems);
344 mSortComparitors.PushBack(CompareItems3D);
345 mSortComparitors.PushBack(CompareItems3DWithClipping);
348 RenderInstructionProcessor::~RenderInstructionProcessor() = default;
350 inline void RenderInstructionProcessor::SortRenderItems(BufferIndex bufferIndex, RenderList& renderList, Layer& layer, bool respectClippingOrder)
352 const uint32_t renderableCount = static_cast<uint32_t>(renderList.Count());
353 // Reserve space if needed.
354 const uint32_t oldcapacity = static_cast<uint32_t>(mSortingHelper.size());
355 if(oldcapacity < renderableCount)
357 mSortingHelper.reserve(renderableCount);
358 // Add real objects (reserve does not construct objects).
359 mSortingHelper.insert(mSortingHelper.begin() + oldcapacity,
360 (renderableCount - oldcapacity),
361 RenderInstructionProcessor::SortAttributes());
365 // Clear extra elements from helper, does not decrease capability.
366 mSortingHelper.resize(renderableCount);
369 // Calculate the sorting value, once per item by calling the layers sort function.
370 // Using an if and two for-loops rather than if inside for as its better for branch prediction.
371 if(layer.UsesDefaultSortFunction())
373 for(uint32_t index = 0; index < renderableCount; ++index)
375 RenderItem& item = renderList.GetItem(index);
379 item.mRenderer->SetSortAttributes(mSortingHelper[index]);
383 mSortingHelper[index].textureSet = item.mTextureSet;
385 // The default sorting function should get inlined here.
386 mSortingHelper[index].zValue = Internal::Layer::ZValue(item.mModelViewMatrix.GetTranslation3()) - static_cast<float>(item.mDepthIndex);
388 // Keep the renderitem pointer in the helper so we can quickly reorder items after sort.
389 mSortingHelper[index].renderItem = &item;
394 const Dali::Layer::SortFunctionType sortFunction = layer.GetSortFunction();
395 for(uint32_t index = 0; index < renderableCount; ++index)
397 RenderItem& item = renderList.GetItem(index);
399 item.mRenderer->SetSortAttributes(mSortingHelper[index]);
402 mSortingHelper[index].textureSet = item.mTextureSet;
404 mSortingHelper[index].zValue = (*sortFunction)(item.mModelViewMatrix.GetTranslation3()) - static_cast<float>(item.mDepthIndex);
406 // Keep the RenderItem pointer in the helper so we can quickly reorder items after sort.
407 mSortingHelper[index].renderItem = &item;
411 // Here we determine which comparitor (of the 3) to use.
414 // 2 is LAYER_3D + Clipping
415 const unsigned int comparitorIndex = layer.GetBehavior() == Dali::Layer::LAYER_3D ? respectClippingOrder ? 2u : 1u : 0u;
417 std::stable_sort(mSortingHelper.begin(), mSortingHelper.end(), mSortComparitors[comparitorIndex]);
419 // Reorder / re-populate the RenderItems in the RenderList to correct order based on the sortinghelper.
420 DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, "Sorted Transparent List:\n");
421 RenderItemContainer::Iterator renderListIter = renderList.GetContainer().Begin();
422 for(uint32_t index = 0; index < renderableCount; ++index, ++renderListIter)
424 *renderListIter = mSortingHelper[index].renderItem;
425 DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, " sortedList[%d] = %p\n", index, mSortingHelper[index].renderItem->mRenderer);
429 void RenderInstructionProcessor::Prepare(BufferIndex updateBufferIndex,
430 SortedLayerPointers& sortedLayers,
431 RenderTask& renderTask,
433 bool hasClippingNodes,
434 RenderInstructionContainer& instructions)
436 // Retrieve the RenderInstruction buffer from the RenderInstructionContainer
437 // then populate with instructions.
438 RenderInstruction& instruction = renderTask.PrepareRenderInstruction(updateBufferIndex);
439 bool viewMatrixHasNotChanged = !renderTask.ViewMatrixUpdated();
440 bool isRenderListAdded = false;
441 bool isRootLayerDirty = false;
443 const Matrix& viewMatrix = renderTask.GetViewMatrix(updateBufferIndex);
444 SceneGraph::Camera& camera = renderTask.GetCamera();
446 const SortedLayersIter endIter = sortedLayers.end();
447 for(SortedLayersIter iter = sortedLayers.begin(); iter != endIter; ++iter)
449 Layer& layer = **iter;
450 const bool tryReuseRenderList(viewMatrixHasNotChanged && layer.CanReuseRenderers(&renderTask.GetCamera()));
451 const bool isLayer3D = layer.GetBehavior() == Dali::Layer::LAYER_3D;
452 RenderList* renderList = nullptr;
454 if(layer.IsRoot() && (layer.GetDirtyFlags() != NodePropertyFlags::NOTHING))
456 // 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
457 isRootLayerDirty = true;
460 if(!layer.colorRenderables.Empty())
462 RenderableContainer& renderables = layer.colorRenderables;
464 if(!SetupRenderList(renderables, layer, instruction, tryReuseRenderList, &renderList))
466 renderList->SetHasColorRenderItems(true);
467 AddRenderersToRenderList(updateBufferIndex,
475 // We only use the clipping version of the sort comparitor if any clipping nodes exist within the RenderList.
476 SortRenderItems(updateBufferIndex, *renderList, layer, hasClippingNodes);
479 isRenderListAdded = true;
482 if(!layer.overlayRenderables.Empty())
484 RenderableContainer& renderables = layer.overlayRenderables;
486 if(!SetupRenderList(renderables, layer, instruction, tryReuseRenderList, &renderList))
488 renderList->SetHasColorRenderItems(false);
489 AddRenderersToRenderList(updateBufferIndex,
497 // Clipping hierarchy is irrelevant when sorting overlay items, so we specify using the non-clipping version of the sort comparitor.
498 SortRenderItems(updateBufferIndex, *renderList, layer, false);
501 isRenderListAdded = true;
505 // Inform the render instruction that all renderers have been added and this frame is complete.
506 instruction.UpdateCompleted();
508 if(isRenderListAdded || instruction.mIsClearColorSet || isRootLayerDirty)
510 instructions.PushBack(updateBufferIndex, &instruction);
514 } // namespace SceneGraph
516 } // namespace Internal