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