919d6f51b6f9e20bae44e1a732dbd26caa15e66d
[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
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   mRenderManager->PostRender();
238 }
239
240 void Core::SceneCreated()
241 {
242   mStage->EmitSceneCreatedSignal();
243
244   mRelayoutController->OnApplicationSceneCreated();
245
246   for(const auto& scene : mScenes)
247   {
248     Dali::Actor sceneRootLayer = scene->GetRootLayer();
249     mRelayoutController->RequestRelayoutTree(sceneRootLayer);
250   }
251 }
252
253 void Core::QueueEvent(const Integration::Event& event)
254 {
255   if(mScenes.size() != 0)
256   {
257     mScenes.front()->QueueEvent(event);
258   }
259 }
260
261 void Core::ProcessEvents()
262 {
263   // Guard against calls to ProcessEvents() during ProcessEvents()
264   if(mProcessingEvent)
265   {
266     DALI_LOG_ERROR("ProcessEvents should not be called from within ProcessEvents!\n");
267     mRenderController.RequestProcessEventsOnIdle(false);
268     return;
269   }
270
271   mProcessingEvent = true;
272   mRelayoutController->SetProcessingCoreEvents(true);
273
274   // Signal that any messages received will be flushed soon
275   mUpdateManager->EventProcessingStarted();
276
277   // Scene could be added or removed while processing the events
278   // Copy the Scene container locally to avoid possibly invalid iterator
279   SceneContainer scenes = mScenes;
280
281   // process events in all scenes
282   for(auto scene : scenes)
283   {
284     scene->ProcessEvents();
285   }
286
287   mNotificationManager->ProcessMessages();
288
289   // Emit signal here to inform listeners that event processing has finished.
290   for(auto scene : scenes)
291   {
292     scene->EmitEventProcessingFinishedSignal();
293   }
294
295   // Run any registered processors
296   RunProcessors();
297
298   // Run the size negotiation after event processing finished signal
299   mRelayoutController->Relayout();
300
301   // Run any registered post processors
302   RunPostProcessors();
303
304   // Rebuild depth tree after event processing has finished
305   for(auto scene : scenes)
306   {
307     scene->RebuildDepthTree();
308   }
309
310   // Flush any queued messages for the update-thread
311   const bool messagesToProcess = mUpdateManager->FlushQueue();
312
313   // Check if the touch or gestures require updates.
314   const bool gestureNeedsUpdate = mGestureEventProcessor->NeedsUpdate();
315   // Check if the next update is forced.
316   const bool forceUpdate = IsNextUpdateForced();
317
318   if(messagesToProcess || gestureNeedsUpdate || forceUpdate)
319   {
320     // tell the render controller to keep update thread running
321     mRenderController.RequestUpdate(forceUpdate);
322   }
323
324   mRelayoutController->SetProcessingCoreEvents(false);
325
326   // ProcessEvents() may now be called again
327   mProcessingEvent = false;
328 }
329
330 uint32_t Core::GetMaximumUpdateCount() const
331 {
332   return MAXIMUM_UPDATE_COUNT;
333 }
334
335 void Core::RegisterProcessor(Integration::Processor& processor, bool postProcessor)
336 {
337   if(postProcessor)
338   {
339     mPostProcessors.PushBack(&processor);
340   }
341   else
342   {
343     mProcessors.PushBack(&processor);
344   }
345 }
346
347 void Core::UnregisterProcessor(Integration::Processor& processor, bool postProcessor)
348 {
349   if(postProcessor)
350   {
351     auto iter = std::find(mPostProcessors.Begin(), mPostProcessors.End(), &processor);
352     if(iter != mPostProcessors.End())
353     {
354       mPostProcessors.Erase(iter);
355       mPostProcessorUnregistered = true;
356     }
357   }
358   else
359   {
360     auto iter = std::find(mProcessors.Begin(), mProcessors.End(), &processor);
361     if(iter != mProcessors.End())
362     {
363       mProcessors.Erase(iter);
364       mProcessorUnregistered = true;
365     }
366   }
367 }
368
369 void Core::RunProcessors()
370 {
371   if(mProcessors.Count() != 0)
372   {
373     DALI_TRACE_BEGIN(gTraceFilter, "DALI_CORE_RUN_PROCESSORS");
374
375     // Copy processor pointers to prevent changes to vector affecting loop iterator.
376     Dali::Vector<Integration::Processor*> processors(mProcessors);
377
378     // To prevent accessing processor unregistered during the loop
379     mProcessorUnregistered = false;
380
381     for(auto processor : processors)
382     {
383       if(processor)
384       {
385         if(!mProcessorUnregistered)
386         {
387           processor->Process(false);
388         }
389         else
390         {
391           // Run processor if the processor is still in the list.
392           // It may be removed during the loop.
393           auto iter = std::find(mProcessors.Begin(), mProcessors.End(), processor);
394           if(iter != mProcessors.End())
395           {
396             processor->Process(false);
397           }
398         }
399       }
400     }
401     DALI_TRACE_END(gTraceFilter, "DALI_CORE_RUN_PROCESSORS");
402   }
403 }
404
405 void Core::RunPostProcessors()
406 {
407   if(mPostProcessors.Count() != 0)
408   {
409     DALI_TRACE_BEGIN(gTraceFilter, "DALI_CORE_RUN_POST_PROCESSORS");
410
411     // Copy processor pointers to prevent changes to vector affecting loop iterator.
412     Dali::Vector<Integration::Processor*> processors(mPostProcessors);
413
414     // To prevent accessing processor unregistered during the loop
415     mPostProcessorUnregistered = false;
416
417     for(auto processor : processors)
418     {
419       if(processor)
420       {
421         if(!mPostProcessorUnregistered)
422         {
423           processor->Process(true);
424         }
425         else
426         {
427           // Run processor if the processor is still in the list.
428           // It may be removed during the loop.
429           auto iter = std::find(mPostProcessors.Begin(), mPostProcessors.End(), processor);
430           if(iter != mPostProcessors.End())
431           {
432             processor->Process(true);
433           }
434         }
435       }
436     }
437     DALI_TRACE_END(gTraceFilter, "DALI_CORE_RUN_POST_PROCESSORS");
438   }
439 }
440
441 StagePtr Core::GetCurrentStage()
442 {
443   return mStage.Get();
444 }
445
446 PlatformAbstraction& Core::GetPlatform()
447 {
448   return mPlatform;
449 }
450
451 UpdateManager& Core::GetUpdateManager()
452 {
453   return *(mUpdateManager);
454 }
455
456 RenderManager& Core::GetRenderManager()
457 {
458   return *(mRenderManager);
459 }
460
461 NotificationManager& Core::GetNotificationManager()
462 {
463   return *(mNotificationManager);
464 }
465
466 ShaderFactory& Core::GetShaderFactory()
467 {
468   return *(mShaderFactory);
469 }
470
471 GestureEventProcessor& Core::GetGestureEventProcessor()
472 {
473   return *(mGestureEventProcessor);
474 }
475
476 RelayoutController& Core::GetRelayoutController()
477 {
478   return *(mRelayoutController.Get());
479 }
480
481 ObjectRegistry& Core::GetObjectRegistry() const
482 {
483   return *(mObjectRegistry.Get());
484 }
485
486 EventThreadServices& Core::GetEventThreadServices()
487 {
488   return *this;
489 }
490
491 PropertyNotificationManager& Core::GetPropertyNotificationManager() const
492 {
493   return *(mPropertyNotificationManager);
494 }
495
496 AnimationPlaylist& Core::GetAnimationPlaylist() const
497 {
498   return *(mAnimationPlaylist);
499 }
500
501 Integration::GlAbstraction& Core::GetGlAbstraction() const
502 {
503   return mGraphicsController.GetGlAbstraction();
504 }
505
506 void Core::AddScene(Scene* scene)
507 {
508   mScenes.push_back(scene);
509 }
510
511 void Core::RemoveScene(Scene* scene)
512 {
513   auto iter = std::find(mScenes.begin(), mScenes.end(), scene);
514   if(iter != mScenes.end())
515   {
516     mScenes.erase(iter);
517   }
518 }
519
520 void Core::CreateThreadLocalStorage()
521 {
522   // a pointer to the ThreadLocalStorage object will be stored in TLS
523   // The ThreadLocalStorage object should be deleted by the Core destructor
524   ThreadLocalStorage* tls = new ThreadLocalStorage(this);
525   tls->Reference();
526 }
527
528 void Core::RegisterObject(Dali::BaseObject* object)
529 {
530   mObjectRegistry = &ThreadLocalStorage::Get().GetObjectRegistry();
531   mObjectRegistry->RegisterObject(object);
532 }
533
534 void Core::UnregisterObject(Dali::BaseObject* object)
535 {
536   mObjectRegistry = &ThreadLocalStorage::Get().GetObjectRegistry();
537   mObjectRegistry->UnregisterObject(object);
538 }
539
540 Integration::RenderController& Core::GetRenderController()
541 {
542   return mRenderController;
543 }
544
545 uint32_t* Core::ReserveMessageSlot(uint32_t size, bool updateScene)
546 {
547   return mUpdateManager->ReserveMessageSlot(size, updateScene);
548 }
549
550 BufferIndex Core::GetEventBufferIndex() const
551 {
552   return mUpdateManager->GetEventBufferIndex();
553 }
554
555 void Core::ForceNextUpdate()
556 {
557   mForceNextUpdate = true;
558 }
559
560 bool Core::IsNextUpdateForced()
561 {
562   bool nextUpdateForced = mForceNextUpdate;
563   mForceNextUpdate      = false;
564   return nextUpdateForced;
565 }
566
567 } // namespace Internal
568
569 } // namespace Dali