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