4916657b87b6837d9442cdc64797b804c482c52b
[platform/core/uifw/dali-core.git] / dali / internal / common / core-impl.cpp
1 /*
2  * Copyright (c) 2021 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/gl-sync-abstraction.h>
28 #include <dali/integration-api/platform-abstraction.h>
29 #include <dali/integration-api/processor-interface.h>
30 #include <dali/integration-api/render-controller.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 #if defined(DEBUG_ENABLED)
64 Debug::Filter* gCoreFilter = Debug::Filter::New(Debug::Concise, false, "LOG_CORE");
65 #endif
66 } // namespace
67
68 namespace Dali
69 {
70 namespace Internal
71 {
72 using Integration::Event;
73 using Integration::GlAbstraction;
74 using Integration::GlContextHelperAbstraction;
75 using Integration::GlSyncAbstraction;
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   mForceNextUpdate(false)
93 {
94   // Create the thread local storage
95   CreateThreadLocalStorage();
96
97   // This does nothing until Core is built with --enable-performance-monitor
98   PERFORMANCE_MONITOR_INIT(platform);
99
100   mNotificationManager = new NotificationManager();
101
102   mAnimationPlaylist = AnimationPlaylist::New();
103
104   mPropertyNotificationManager = PropertyNotificationManager::New();
105
106   mRenderTaskProcessor = new SceneGraph::RenderTaskProcessor();
107
108   mRenderManager = RenderManager::New(graphicsController, depthBufferAvailable, stencilBufferAvailable, partialUpdateAvailable);
109
110   RenderQueue& renderQueue = mRenderManager->GetRenderQueue();
111
112   mDiscardQueue = new DiscardQueue(renderQueue);
113
114   mUpdateManager = new UpdateManager(*mNotificationManager,
115                                      *mAnimationPlaylist,
116                                      *mPropertyNotificationManager,
117                                      *mDiscardQueue,
118                                      renderController,
119                                      *mRenderManager,
120                                      renderQueue,
121                                      *mRenderTaskProcessor);
122
123   mRenderManager->SetShaderSaver(*mUpdateManager);
124
125   mObjectRegistry = ObjectRegistry::New();
126
127   mStage = IntrusivePtr<Stage>(Stage::New(*mUpdateManager));
128
129   // This must be called after stage is created but before stage initialization
130   mRelayoutController = IntrusivePtr<RelayoutController>(new RelayoutController(mRenderController));
131
132   mGestureEventProcessor = new GestureEventProcessor(*mUpdateManager, mRenderController);
133
134   mShaderFactory = new ShaderFactory();
135   mUpdateManager->SetShaderSaver(*mShaderFactory);
136
137   GetImplementation(Dali::TypeRegistry::Get()).CallInitFunctions();
138 }
139
140 Core::~Core()
141 {
142   /*
143    * The order of destructing these singletons is important!!!
144    */
145
146   // clear the thread local storage first
147   // allows core to be created / deleted many times in the same thread (how TET cases work).
148   // Do this before mStage.Reset() so Stage::IsInstalled() returns false
149   ThreadLocalStorage* tls = ThreadLocalStorage::GetInternal();
150   if(tls)
151   {
152     tls->Remove();
153     tls->Unreference();
154   }
155
156   mObjectRegistry.Reset();
157
158   // Stop relayout requests being raised on stage destruction
159   mRelayoutController.Reset();
160
161   // remove (last?) reference to stage
162   mStage.Reset();
163 }
164
165 void Core::Initialize()
166 {
167   mStage->Initialize(*mScenes[0]);
168 }
169
170 Integration::ContextNotifierInterface* Core::GetContextNotifier()
171 {
172   return mStage.Get();
173 }
174
175 void Core::RecoverFromContextLoss()
176 {
177   DALI_LOG_INFO(gCoreFilter, Debug::Verbose, "Core::RecoverFromContextLoss()\n");
178
179   mStage->GetRenderTaskList().RecoverFromContextLoss(); // Re-trigger render-tasks
180 }
181
182 void Core::ContextCreated()
183 {
184   mRenderManager->ContextCreated();
185 }
186
187 void Core::ContextDestroyed()
188 {
189   mRenderManager->ContextDestroyed();
190 }
191
192 void Core::Update(float elapsedSeconds, uint32_t lastVSyncTimeMilliseconds, uint32_t nextVSyncTimeMilliseconds, Integration::UpdateStatus& status, bool renderToFboEnabled, bool isRenderingToFbo)
193 {
194   // set the time delta so adaptor can easily print FPS with a release build with 0 as
195   // it is cached by frametime
196   status.secondsFromLastFrame = elapsedSeconds;
197
198   // Render returns true when there are updates on the stage or one or more animations are completed.
199   // Use the estimated time diff till we render as the elapsed time.
200   status.keepUpdating = mUpdateManager->Update(elapsedSeconds,
201                                                lastVSyncTimeMilliseconds,
202                                                nextVSyncTimeMilliseconds,
203                                                renderToFboEnabled,
204                                                isRenderingToFbo);
205
206   // Check the Notification Manager message queue to set needsNotification
207   status.needsNotification = mNotificationManager->MessagesToProcess();
208
209   // No need to keep update running if there are notifications to process.
210   // Any message to update will wake it up anyways
211 }
212
213 void Core::PreRender(RenderStatus& status, bool forceClear, bool uploadOnly)
214 {
215   mRenderManager->PreRender(status, forceClear, uploadOnly);
216 }
217
218 void Core::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
219 {
220   mRenderManager->PreRender(scene, damagedRects);
221 }
222
223 void Core::RenderScene(RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
224 {
225   mRenderManager->RenderScene(status, scene, renderToFbo);
226 }
227
228 void Core::RenderScene(RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
229 {
230   mRenderManager->RenderScene(status, scene, renderToFbo, clippingRect);
231 }
232
233 void Core::PostRender(bool uploadOnly)
234 {
235   mRenderManager->PostRender(uploadOnly);
236 }
237
238 void Core::SceneCreated()
239 {
240   mStage->EmitSceneCreatedSignal();
241
242   mRelayoutController->OnApplicationSceneCreated();
243
244   for(const auto& scene : mScenes)
245   {
246     Dali::Actor sceneRootLayer = scene->GetRootLayer();
247     mRelayoutController->RequestRelayoutTree(sceneRootLayer);
248   }
249 }
250
251 void Core::QueueEvent(const Integration::Event& event)
252 {
253   if(mScenes.size() != 0)
254   {
255     mScenes.front()->QueueEvent(event);
256   }
257 }
258
259 void Core::ProcessEvents()
260 {
261   // Guard against calls to ProcessEvents() during ProcessEvents()
262   if(mProcessingEvent)
263   {
264     DALI_LOG_ERROR("ProcessEvents should not be called from within ProcessEvents!\n");
265     mRenderController.RequestProcessEventsOnIdle(false);
266     return;
267   }
268
269   mProcessingEvent = true;
270   mRelayoutController->SetProcessingCoreEvents(true);
271
272   // Signal that any messages received will be flushed soon
273   mUpdateManager->EventProcessingStarted();
274
275   // Scene could be added or removed while processing the events
276   // Copy the Scene container locally to avoid possibly invalid iterator
277   SceneContainer scenes = mScenes;
278
279   // process events in all scenes
280   for(auto scene : scenes)
281   {
282     scene->ProcessEvents();
283   }
284
285   mNotificationManager->ProcessMessages();
286
287   // Emit signal here to inform listeners that event processing has finished.
288   for(auto scene : scenes)
289   {
290     scene->EmitEventProcessingFinishedSignal();
291   }
292
293   // Run any registered processors
294   RunProcessors();
295
296   // Run the size negotiation after event processing finished signal
297   mRelayoutController->Relayout();
298
299   // Rebuild depth tree after event processing has finished
300   for(auto scene : scenes)
301   {
302     scene->RebuildDepthTree();
303   }
304
305   // Flush any queued messages for the update-thread
306   const bool messagesToProcess = mUpdateManager->FlushQueue();
307
308   // Check if the touch or gestures require updates.
309   const bool gestureNeedsUpdate = mGestureEventProcessor->NeedsUpdate();
310   // Check if the next update is forced.
311   const bool forceUpdate = IsNextUpdateForced();
312
313   if(messagesToProcess || gestureNeedsUpdate || forceUpdate)
314   {
315     // tell the render controller to keep update thread running
316     mRenderController.RequestUpdate(forceUpdate);
317   }
318
319   mRelayoutController->SetProcessingCoreEvents(false);
320
321   // ProcessEvents() may now be called again
322   mProcessingEvent = false;
323 }
324
325 uint32_t Core::GetMaximumUpdateCount() const
326 {
327   return MAXIMUM_UPDATE_COUNT;
328 }
329
330 void Core::RegisterProcessor(Integration::Processor& processor)
331 {
332   mProcessors.PushBack(&processor);
333 }
334
335 void Core::UnregisterProcessor(Integration::Processor& processor)
336 {
337   auto iter = std::find(mProcessors.Begin(), mProcessors.End(), &processor);
338   if(iter != mProcessors.End())
339   {
340     mProcessors.Erase(iter);
341   }
342 }
343
344 void Core::RunProcessors()
345 {
346   // Copy processor pointers to prevent changes to vector affecting loop iterator.
347   Dali::Vector<Integration::Processor*> processors(mProcessors);
348
349   for(auto processor : processors)
350   {
351     if(processor)
352     {
353       processor->Process();
354     }
355   }
356 }
357
358 StagePtr Core::GetCurrentStage()
359 {
360   return mStage.Get();
361 }
362
363 PlatformAbstraction& Core::GetPlatform()
364 {
365   return mPlatform;
366 }
367
368 UpdateManager& Core::GetUpdateManager()
369 {
370   return *(mUpdateManager);
371 }
372
373 RenderManager& Core::GetRenderManager()
374 {
375   return *(mRenderManager);
376 }
377
378 NotificationManager& Core::GetNotificationManager()
379 {
380   return *(mNotificationManager);
381 }
382
383 ShaderFactory& Core::GetShaderFactory()
384 {
385   return *(mShaderFactory);
386 }
387
388 GestureEventProcessor& Core::GetGestureEventProcessor()
389 {
390   return *(mGestureEventProcessor);
391 }
392
393 RelayoutController& Core::GetRelayoutController()
394 {
395   return *(mRelayoutController.Get());
396 }
397
398 ObjectRegistry& Core::GetObjectRegistry() const
399 {
400   return *(mObjectRegistry.Get());
401 }
402
403 EventThreadServices& Core::GetEventThreadServices()
404 {
405   return *this;
406 }
407
408 PropertyNotificationManager& Core::GetPropertyNotificationManager() const
409 {
410   return *(mPropertyNotificationManager);
411 }
412
413 AnimationPlaylist& Core::GetAnimationPlaylist() const
414 {
415   return *(mAnimationPlaylist);
416 }
417
418 Integration::GlAbstraction& Core::GetGlAbstraction() const
419 {
420   return mGraphicsController.GetGlAbstraction();
421 }
422
423 void Core::AddScene(Scene* scene)
424 {
425   mScenes.push_back(scene);
426 }
427
428 void Core::RemoveScene(Scene* scene)
429 {
430   auto iter = std::find(mScenes.begin(), mScenes.end(), scene);
431   if(iter != mScenes.end())
432   {
433     mScenes.erase(iter);
434   }
435 }
436
437 void Core::CreateThreadLocalStorage()
438 {
439   // a pointer to the ThreadLocalStorage object will be stored in TLS
440   // The ThreadLocalStorage object should be deleted by the Core destructor
441   ThreadLocalStorage* tls = new ThreadLocalStorage(this);
442   tls->Reference();
443 }
444
445 void Core::RegisterObject(Dali::BaseObject* object)
446 {
447   mObjectRegistry = &ThreadLocalStorage::Get().GetObjectRegistry();
448   mObjectRegistry->RegisterObject(object);
449 }
450
451 void Core::UnregisterObject(Dali::BaseObject* object)
452 {
453   mObjectRegistry = &ThreadLocalStorage::Get().GetObjectRegistry();
454   mObjectRegistry->UnregisterObject(object);
455 }
456
457 Integration::RenderController& Core::GetRenderController()
458 {
459   return mRenderController;
460 }
461
462 uint32_t* Core::ReserveMessageSlot(uint32_t size, bool updateScene)
463 {
464   return mUpdateManager->ReserveMessageSlot(size, updateScene);
465 }
466
467 BufferIndex Core::GetEventBufferIndex() const
468 {
469   return mUpdateManager->GetEventBufferIndex();
470 }
471
472 void Core::ForceNextUpdate()
473 {
474   mForceNextUpdate = true;
475 }
476
477 bool Core::IsNextUpdateForced()
478 {
479   bool nextUpdateForced = mForceNextUpdate;
480   mForceNextUpdate      = false;
481   return nextUpdateForced;
482 }
483
484 } // namespace Internal
485
486 } // namespace Dali