Print the number of loop count when we trace iteration
[platform/core/uifw/dali-core.git] / dali / internal / common / core-impl.cpp
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/common/core-impl.h>
20
21 // INTERNAL INCLUDES
22 #include <dali/graphics-api/graphics-controller.h>
23 #include <dali/integration-api/core.h>
24 #include <dali/integration-api/debug.h>
25 #include <dali/integration-api/events/event.h>
26 #include <dali/integration-api/gl-context-helper-abstraction.h>
27 #include <dali/integration-api/platform-abstraction.h>
28 #include <dali/integration-api/processor-interface.h>
29 #include <dali/integration-api/render-controller.h>
30 #include <dali/integration-api/trace.h>
31
32 #include <dali/internal/event/actors/actor-impl.h>
33 #include <dali/internal/event/animation/animation-playlist.h>
34 #include <dali/internal/event/common/event-thread-services.h>
35 #include <dali/internal/event/common/notification-manager.h>
36 #include <dali/internal/event/common/property-notification-manager.h>
37 #include <dali/internal/event/common/stage-impl.h>
38 #include <dali/internal/event/common/thread-local-storage.h>
39 #include <dali/internal/event/common/type-registry-impl.h>
40 #include <dali/internal/event/effects/shader-factory.h>
41 #include <dali/internal/event/events/event-processor.h>
42 #include <dali/internal/event/events/gesture-event-processor.h>
43 #include <dali/internal/event/render-tasks/render-task-list-impl.h>
44 #include <dali/internal/event/size-negotiation/relayout-controller-impl.h>
45
46 #include <dali/internal/update/common/discard-queue.h>
47 #include <dali/internal/update/manager/render-task-processor.h>
48 #include <dali/internal/update/manager/update-manager.h>
49
50 #include <dali/internal/render/common/performance-monitor.h>
51 #include <dali/internal/render/common/render-manager.h>
52
53 using Dali::Internal::SceneGraph::RenderManager;
54 using Dali::Internal::SceneGraph::RenderQueue;
55 using Dali::Internal::SceneGraph::UpdateManager;
56
57 namespace
58 {
59 // The Update for frame N+1 may be processed whilst frame N is being rendered.
60 const uint32_t MAXIMUM_UPDATE_COUNT = 2u;
61
62 DALI_INIT_TRACE_FILTER(gTraceFilter, DALI_TRACE_PERFORMANCE_MARKER, false);
63
64 #if defined(DEBUG_ENABLED)
65 Debug::Filter* gCoreFilter = Debug::Filter::New(Debug::Concise, false, "LOG_CORE");
66 #endif
67 } // namespace
68
69 namespace Dali
70 {
71 namespace Internal
72 {
73 using Integration::Event;
74 using Integration::GlAbstraction;
75 using Integration::GlContextHelperAbstraction;
76 using Integration::PlatformAbstraction;
77 using Integration::RenderController;
78 using Integration::RenderStatus;
79 using Integration::UpdateStatus;
80
81 Core::Core(RenderController&                   renderController,
82            PlatformAbstraction&                platform,
83            Graphics::Controller&               graphicsController,
84            Integration::RenderToFrameBuffer    renderToFboEnabled,
85            Integration::DepthBufferAvailable   depthBufferAvailable,
86            Integration::StencilBufferAvailable stencilBufferAvailable,
87            Integration::PartialUpdateAvailable partialUpdateAvailable)
88 : mRenderController(renderController),
89   mPlatform(platform),
90   mGraphicsController(graphicsController),
91   mProcessingEvent(false),
92   mProcessorUnregistered(false),
93   mPostProcessorUnregistered(false),
94   mRelayoutFlush(false)
95 {
96   // Create the thread local storage
97   CreateThreadLocalStorage();
98
99   // This does nothing until Core is built with --enable-performance-monitor
100   PERFORMANCE_MONITOR_INIT(platform);
101
102   mNotificationManager = new NotificationManager();
103
104   mAnimationPlaylist = AnimationPlaylist::New();
105
106   mPropertyNotificationManager = PropertyNotificationManager::New();
107
108   mRenderTaskProcessor = new SceneGraph::RenderTaskProcessor();
109
110   mRenderManager = RenderManager::New(graphicsController, depthBufferAvailable, stencilBufferAvailable, partialUpdateAvailable);
111
112   RenderQueue& renderQueue = mRenderManager->GetRenderQueue();
113
114   mUpdateManager = new UpdateManager(*mNotificationManager,
115                                      *mAnimationPlaylist,
116                                      *mPropertyNotificationManager,
117                                      renderController,
118                                      *mRenderManager,
119                                      renderQueue,
120                                      *mRenderTaskProcessor);
121
122   mRenderManager->SetShaderSaver(*mUpdateManager);
123
124   mObjectRegistry = ObjectRegistry::New();
125
126   mStage = IntrusivePtr<Stage>(Stage::New(*mUpdateManager));
127
128   // This must be called after stage is created but before stage initialization
129   mRelayoutController = IntrusivePtr<RelayoutController>(new RelayoutController(mRenderController));
130
131   mGestureEventProcessor = new GestureEventProcessor(*mUpdateManager, mRenderController);
132
133   mShaderFactory = new ShaderFactory();
134   mUpdateManager->SetShaderSaver(*mShaderFactory);
135
136   GetImplementation(Dali::TypeRegistry::Get()).CallInitFunctions();
137
138   DALI_LOG_RELEASE_INFO("Node size: %lu\n", sizeof(Dali::Internal::SceneGraph::Node));
139   DALI_LOG_RELEASE_INFO("Renderer size: %lu\n", sizeof(Dali::Internal::SceneGraph::Renderer));
140   DALI_LOG_RELEASE_INFO("RenderItem size: %lu\n", sizeof(Dali::Internal::SceneGraph::RenderItem));
141 }
142
143 Core::~Core()
144 {
145   /*
146    * The order of destructing these singletons is important!!!
147    */
148
149   // clear the thread local storage first
150   // allows core to be created / deleted many times in the same thread (how TET cases work).
151   // Do this before mStage.Reset() so Stage::IsInstalled() returns false
152   ThreadLocalStorage* tls = ThreadLocalStorage::GetInternal();
153   if(tls)
154   {
155     tls->Remove();
156     tls->Unreference();
157   }
158
159   mObjectRegistry.Reset();
160
161   // Stop relayout requests being raised on stage destruction
162   mRelayoutController.Reset();
163
164   // remove (last?) reference to stage
165   mStage.Reset();
166 }
167
168 void Core::Initialize()
169 {
170   mStage->Initialize(*mScenes[0]);
171 }
172
173 Integration::ContextNotifierInterface* Core::GetContextNotifier()
174 {
175   return mStage.Get();
176 }
177
178 void Core::RecoverFromContextLoss()
179 {
180   DALI_LOG_INFO(gCoreFilter, Debug::Verbose, "Core::RecoverFromContextLoss()\n");
181
182   mStage->GetRenderTaskList().RecoverFromContextLoss(); // Re-trigger render-tasks
183 }
184
185 void Core::ContextCreated()
186 {
187 }
188
189 void Core::ContextDestroyed()
190 {
191 }
192
193 void Core::Update(float elapsedSeconds, uint32_t lastVSyncTimeMilliseconds, uint32_t nextVSyncTimeMilliseconds, Integration::UpdateStatus& status, bool renderToFboEnabled, bool isRenderingToFbo, bool uploadOnly)
194 {
195   // set the time delta so adaptor can easily print FPS with a release build with 0 as
196   // it is cached by frametime
197   status.secondsFromLastFrame = elapsedSeconds;
198
199   // Render returns true when there are updates on the stage or one or more animations are completed.
200   // Use the estimated time diff till we render as the elapsed time.
201   status.keepUpdating = mUpdateManager->Update(elapsedSeconds,
202                                                lastVSyncTimeMilliseconds,
203                                                nextVSyncTimeMilliseconds,
204                                                renderToFboEnabled,
205                                                isRenderingToFbo,
206                                                uploadOnly);
207
208   // Check the Notification Manager message queue to set needsNotification
209   status.needsNotification = mNotificationManager->MessagesToProcess();
210
211   // No need to keep update running if there are notifications to process.
212   // Any message to update will wake it up anyways
213 }
214
215 void Core::PreRender(RenderStatus& status, bool forceClear)
216 {
217   mRenderManager->PreRender(status, forceClear);
218 }
219
220 void Core::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
221 {
222   mRenderManager->PreRender(scene, damagedRects);
223 }
224
225 void Core::RenderScene(RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
226 {
227   mRenderManager->RenderScene(status, scene, renderToFbo);
228 }
229
230 void Core::RenderScene(RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
231 {
232   mRenderManager->RenderScene(status, scene, renderToFbo, clippingRect);
233 }
234
235 void Core::PostRender()
236 {
237   mUpdateManager->PostRender();
238   mRenderManager->PostRender();
239 }
240
241 void Core::SceneCreated()
242 {
243   mStage->EmitSceneCreatedSignal();
244
245   mRelayoutController->OnApplicationSceneCreated();
246
247   for(const auto& scene : mScenes)
248   {
249     Dali::Actor sceneRootLayer = scene->GetRootLayer();
250     mRelayoutController->RequestRelayoutTree(sceneRootLayer);
251   }
252 }
253
254 void Core::QueueEvent(const Integration::Event& event)
255 {
256   if(mScenes.size() != 0)
257   {
258     mScenes.front()->QueueEvent(event);
259   }
260 }
261
262 void Core::ForceRelayout()
263 {
264   if(mRelayoutFlush)
265   {
266     DALI_LOG_ERROR("ForceRelayout should not be called from within RelayoutAndFlush!\n");
267     return;
268   }
269
270   // Scene could be added or removed while processing the events
271   // Copy the Scene container locally to avoid possibly invalid iterator
272   SceneContainer scenes = mScenes;
273
274   RelayoutAndFlush(scenes);
275 }
276
277 void Core::ProcessEvents()
278 {
279   // Guard against calls to ProcessEvents() during ProcessEvents()
280   if(mProcessingEvent)
281   {
282     DALI_LOG_ERROR("ProcessEvents should not be called from within ProcessEvents!\n");
283     mRenderController.RequestProcessEventsOnIdle();
284     return;
285   }
286
287   mProcessingEvent = true;
288   mRelayoutController->SetProcessingCoreEvents(true);
289
290   // Signal that any messages received will be flushed soon
291   mUpdateManager->EventProcessingStarted();
292
293   // Scene could be added or removed while processing the events
294   // Copy the Scene container locally to avoid possibly invalid iterator
295   SceneContainer scenes = mScenes;
296
297   // process events in all scenes
298   for(auto scene : scenes)
299   {
300     scene->ProcessEvents();
301   }
302
303   mNotificationManager->ProcessMessages();
304
305   // Emit signal here to inform listeners that event processing has finished.
306   for(auto scene : scenes)
307   {
308     scene->EmitEventProcessingFinishedSignal();
309   }
310
311   RelayoutAndFlush(scenes);
312
313   mUpdateManager->EventProcessingFinished();
314
315   // Check if the touch or gestures require updates.
316   const bool gestureNeedsUpdate = mGestureEventProcessor->NeedsUpdate();
317
318   if(gestureNeedsUpdate)
319   {
320     // tell the render controller to keep update thread running
321     mRenderController.RequestUpdate();
322   }
323
324   mRelayoutController->SetProcessingCoreEvents(false);
325
326   // ProcessEvents() may now be called again
327   mProcessingEvent = false;
328 }
329
330 void Core::RelayoutAndFlush(SceneContainer& scenes)
331 {
332   if(mRelayoutFlush)
333   {
334     DALI_LOG_ERROR("RelayoutAndFlush should not be called from within RelayoutAndFlush!\n");
335     return;
336   }
337
338   const bool isProcessEvents = mProcessingEvent;
339
340   if(!isProcessEvents)
341   {
342     // Fake that we are in ProcessEvents()
343     mProcessingEvent = true;
344     mRelayoutController->SetProcessingCoreEvents(true);
345
346     // Signal that any messages received will be flushed soon
347     mUpdateManager->EventProcessingStarted();
348   }
349
350   mRelayoutFlush = true;
351
352   // Run any registered processors
353   RunProcessors();
354
355   // Run the size negotiation after event processing finished signal
356   mRelayoutController->Relayout();
357
358   // Run any registered post processors
359   RunPostProcessors();
360
361   // Rebuild depth tree after event processing has finished
362   for(auto& scene : scenes)
363   {
364     scene->RebuildDepthTree();
365   }
366
367   // Flush any queued messages for the update-thread
368   const bool messagesToProcess = mUpdateManager->FlushQueue();
369
370   if(messagesToProcess)
371   {
372     // tell the render controller to keep update thread running
373     mRenderController.RequestUpdate();
374   }
375
376   mRelayoutFlush = false;
377
378   if(!isProcessEvents)
379   {
380     // Revert fake informations
381     mProcessingEvent = false;
382     mRelayoutController->SetProcessingCoreEvents(false);
383
384     mUpdateManager->EventProcessingFinished();
385   }
386 }
387
388 uint32_t Core::GetMaximumUpdateCount() const
389 {
390   return MAXIMUM_UPDATE_COUNT;
391 }
392
393 void Core::RegisterProcessor(Integration::Processor& processor, bool postProcessor)
394 {
395   if(postProcessor)
396   {
397     mPostProcessors.PushBack(&processor);
398   }
399   else
400   {
401     mProcessors.PushBack(&processor);
402   }
403 }
404
405 void Core::UnregisterProcessor(Integration::Processor& processor, bool postProcessor)
406 {
407   if(postProcessor)
408   {
409     auto iter = std::find(mPostProcessors.Begin(), mPostProcessors.End(), &processor);
410     if(iter != mPostProcessors.End())
411     {
412       mPostProcessors.Erase(iter);
413       mPostProcessorUnregistered = true;
414     }
415   }
416   else
417   {
418     auto iter = std::find(mProcessors.Begin(), mProcessors.End(), &processor);
419     if(iter != mProcessors.End())
420     {
421       mProcessors.Erase(iter);
422       mProcessorUnregistered = true;
423     }
424   }
425 }
426
427 void Core::RunProcessors()
428 {
429   if(mProcessors.Count() != 0)
430   {
431 #ifdef TRACE_ENABLED
432     if(gTraceFilter && gTraceFilter->IsTraceEnabled())
433     {
434       std::ostringstream stream;
435       stream << "[" << mProcessors.Count() << "]";
436       DALI_TRACE_BEGIN_WITH_MESSAGE(gTraceFilter, "DALI_CORE_RUN_PROCESSORS", stream.str().c_str());
437     }
438 #endif
439
440     // Copy processor pointers to prevent changes to vector affecting loop iterator.
441     Dali::Vector<Integration::Processor*> processors(mProcessors);
442
443     // To prevent accessing processor unregistered during the loop
444     mProcessorUnregistered = false;
445
446     for(auto processor : processors)
447     {
448       if(processor)
449       {
450         if(!mProcessorUnregistered)
451         {
452           processor->Process(false);
453         }
454         else
455         {
456           // Run processor if the processor is still in the list.
457           // It may be removed during the loop.
458           auto iter = std::find(mProcessors.Begin(), mProcessors.End(), processor);
459           if(iter != mProcessors.End())
460           {
461             processor->Process(false);
462           }
463         }
464       }
465     }
466 #ifdef TRACE_ENABLED
467     if(gTraceFilter && gTraceFilter->IsTraceEnabled())
468     {
469       std::ostringstream stream;
470       stream << "[" << mProcessors.Count();
471       if(mProcessorUnregistered)
472       {
473         stream << ", processor changed";
474       }
475       stream << "]";
476       DALI_TRACE_END_WITH_MESSAGE(gTraceFilter, "DALI_CORE_RUN_PROCESSORS", stream.str().c_str());
477     }
478 #endif
479   }
480 }
481
482 void Core::RunPostProcessors()
483 {
484   if(mPostProcessors.Count() != 0)
485   {
486 #ifdef TRACE_ENABLED
487     if(gTraceFilter && gTraceFilter->IsTraceEnabled())
488     {
489       std::ostringstream stream;
490       stream << "[" << mPostProcessors.Count() << "]";
491       DALI_TRACE_BEGIN_WITH_MESSAGE(gTraceFilter, "DALI_CORE_RUN_POST_PROCESSORS", stream.str().c_str());
492     }
493 #endif
494
495     // Copy processor pointers to prevent changes to vector affecting loop iterator.
496     Dali::Vector<Integration::Processor*> processors(mPostProcessors);
497
498     // To prevent accessing processor unregistered during the loop
499     mPostProcessorUnregistered = false;
500
501     for(auto processor : processors)
502     {
503       if(processor)
504       {
505         if(!mPostProcessorUnregistered)
506         {
507           processor->Process(true);
508         }
509         else
510         {
511           // Run processor if the processor is still in the list.
512           // It may be removed during the loop.
513           auto iter = std::find(mPostProcessors.Begin(), mPostProcessors.End(), processor);
514           if(iter != mPostProcessors.End())
515           {
516             processor->Process(true);
517           }
518         }
519       }
520     }
521
522 #ifdef TRACE_ENABLED
523     if(gTraceFilter && gTraceFilter->IsTraceEnabled())
524     {
525       std::ostringstream stream;
526       stream << "[" << mPostProcessors.Count();
527       if(mPostProcessorUnregistered)
528       {
529         stream << ", post processor changed";
530       }
531       stream << "]";
532       DALI_TRACE_END_WITH_MESSAGE(gTraceFilter, "DALI_CORE_RUN_POST_PROCESSORS", stream.str().c_str());
533     }
534 #endif
535   }
536 }
537
538 StagePtr Core::GetCurrentStage()
539 {
540   return mStage.Get();
541 }
542
543 PlatformAbstraction& Core::GetPlatform()
544 {
545   return mPlatform;
546 }
547
548 UpdateManager& Core::GetUpdateManager()
549 {
550   return *(mUpdateManager);
551 }
552
553 RenderManager& Core::GetRenderManager()
554 {
555   return *(mRenderManager);
556 }
557
558 NotificationManager& Core::GetNotificationManager()
559 {
560   return *(mNotificationManager);
561 }
562
563 ShaderFactory& Core::GetShaderFactory()
564 {
565   return *(mShaderFactory);
566 }
567
568 GestureEventProcessor& Core::GetGestureEventProcessor()
569 {
570   return *(mGestureEventProcessor);
571 }
572
573 RelayoutController& Core::GetRelayoutController()
574 {
575   return *(mRelayoutController.Get());
576 }
577
578 ObjectRegistry& Core::GetObjectRegistry() const
579 {
580   return *(mObjectRegistry.Get());
581 }
582
583 void Core::LogMemoryPools() const
584 {
585   uint32_t animationPoolCapacity    = SceneGraph::Animation::GetMemoryPoolCapacity();
586   uint32_t renderItemPoolCapacity   = SceneGraph::RenderItem::GetMemoryPoolCapacity();
587   uint32_t relayoutItemPoolCapacity = mRelayoutController->GetMemoryPoolCapacity();
588   uint32_t rendererPoolCapacity     = SceneGraph::Renderer::GetMemoryPoolCapacity();
589   uint32_t textureSetPoolCapacity   = SceneGraph::TextureSet::GetMemoryPoolCapacity();
590   uint32_t renderTaskPoolCapacity   = SceneGraph::RenderTaskList::GetMemoryPoolCapacity();
591   uint32_t nodePoolCapacity         = SceneGraph::Node::GetMemoryPoolCapacity();
592
593   DALI_LOG_RELEASE_INFO(
594     "\nMemory Pool capacities:\n"
595     "  Animations:    %lu\n"
596     "  RenderItems:   %lu\n"
597     "  RelayoutItems: %lu\n"
598     "  Renderers:     %lu\n"
599     "  TextureSets:   %lu\n"
600     "  RenderTasks:   %lu\n"
601     "  Nodes:         %lu\n",
602     animationPoolCapacity,
603     renderItemPoolCapacity,
604     relayoutItemPoolCapacity,
605     rendererPoolCapacity,
606     textureSetPoolCapacity,
607     renderTaskPoolCapacity,
608     nodePoolCapacity);
609
610   uint32_t updateQCapacity = mUpdateManager->GetUpdateMessageQueueCapacity();
611   uint32_t renderQCapacity = mUpdateManager->GetRenderMessageQueueCapacity();
612
613   DALI_LOG_RELEASE_INFO(
614     "\nMessage Queue capacities:\n"
615     "  UpdateQueue: %lu\n"
616     "  RenderQueue: %lu\n",
617     updateQCapacity,
618     renderQCapacity);
619
620   size_t renderInstructionCapacity = mUpdateManager->GetRenderInstructionCapacity();
621   DALI_LOG_RELEASE_INFO("\nRenderInstruction capacity: %lu\n", renderInstructionCapacity);
622 }
623
624 EventThreadServices& Core::GetEventThreadServices()
625 {
626   return *this;
627 }
628
629 PropertyNotificationManager& Core::GetPropertyNotificationManager() const
630 {
631   return *(mPropertyNotificationManager);
632 }
633
634 AnimationPlaylist& Core::GetAnimationPlaylist() const
635 {
636   return *(mAnimationPlaylist);
637 }
638
639 Integration::GlAbstraction& Core::GetGlAbstraction() const
640 {
641   return mGraphicsController.GetGlAbstraction();
642 }
643
644 void Core::AddScene(Scene* scene)
645 {
646   mScenes.push_back(scene);
647 }
648
649 void Core::RemoveScene(Scene* scene)
650 {
651   auto iter = std::find(mScenes.begin(), mScenes.end(), scene);
652   if(iter != mScenes.end())
653   {
654     mScenes.erase(iter);
655   }
656 }
657
658 void Core::CreateThreadLocalStorage()
659 {
660   // a pointer to the ThreadLocalStorage object will be stored in TLS
661   // The ThreadLocalStorage object should be deleted by the Core destructor
662   ThreadLocalStorage* tls = new ThreadLocalStorage(this);
663   tls->Reference();
664 }
665
666 void Core::RegisterObject(Dali::BaseObject* object)
667 {
668   mObjectRegistry = &ThreadLocalStorage::Get().GetObjectRegistry();
669   mObjectRegistry->RegisterObject(object);
670 }
671
672 void Core::UnregisterObject(Dali::BaseObject* object)
673 {
674   mObjectRegistry = &ThreadLocalStorage::Get().GetObjectRegistry();
675   mObjectRegistry->UnregisterObject(object);
676 }
677
678 Integration::RenderController& Core::GetRenderController()
679 {
680   return mRenderController;
681 }
682
683 uint32_t* Core::ReserveMessageSlot(uint32_t size, bool updateScene)
684 {
685   return mUpdateManager->ReserveMessageSlot(size, updateScene);
686 }
687
688 BufferIndex Core::GetEventBufferIndex() const
689 {
690   return mUpdateManager->GetEventBufferIndex();
691 }
692
693 } // namespace Internal
694
695 } // namespace Dali