Merge "Valgrind detected TextureSet leak and invalid access" into devel/master
[platform/core/uifw/dali-core.git] / dali / internal / common / core-impl.cpp
1 /*
2  * Copyright (c) 2016 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/system-overlay.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-sync-abstraction.h>
27 #include <dali/integration-api/platform-abstraction.h>
28 #include <dali/integration-api/render-controller.h>
29
30 #include <dali/internal/event/actors/actor-impl.h>
31 #include <dali/internal/event/animation/animation-playlist.h>
32 #include <dali/internal/event/common/notification-manager.h>
33 #include <dali/internal/event/common/property-notification-manager.h>
34 #include <dali/internal/event/common/stage-impl.h>
35 #include <dali/internal/event/common/thread-local-storage.h>
36 #include <dali/internal/event/common/type-registry-impl.h>
37 #include <dali/internal/event/effects/shader-factory.h>
38 #include <dali/internal/event/events/event-processor.h>
39 #include <dali/internal/event/events/gesture-event-processor.h>
40 #include <dali/internal/event/render-tasks/render-task-list-impl.h>
41 #include <dali/internal/event/size-negotiation/relayout-controller-impl.h>
42
43 #include <dali/internal/update/common/discard-queue.h>
44 #include <dali/internal/update/manager/update-manager.h>
45 #include <dali/internal/update/manager/render-task-processor.h>
46
47 #include <dali/internal/render/common/performance-monitor.h>
48 #include <dali/internal/render/common/render-manager.h>
49 #include <dali/internal/render/gl-resources/context.h>
50
51 using Dali::Internal::SceneGraph::UpdateManager;
52 using Dali::Internal::SceneGraph::RenderManager;
53 using Dali::Internal::SceneGraph::DiscardQueue;
54 using Dali::Internal::SceneGraph::RenderQueue;
55
56 namespace
57 {
58 // The Update for frame N+1 may be processed whilst frame N is being rendered.
59 const unsigned int MAXIMUM_UPDATE_COUNT = 2u;
60
61 #if defined(DEBUG_ENABLED)
62 Debug::Filter* gCoreFilter = Debug::Filter::New(Debug::Concise, false, "LOG_CORE");
63 #endif
64 }
65
66 namespace Dali
67 {
68
69 namespace Internal
70 {
71
72 using Integration::RenderController;
73 using Integration::PlatformAbstraction;
74 using Integration::GlSyncAbstraction;
75 using Integration::GestureManager;
76 using Integration::GlAbstraction;
77 using Integration::Event;
78 using Integration::UpdateStatus;
79 using Integration::RenderStatus;
80
81 Core::Core( RenderController& renderController, PlatformAbstraction& platform,
82             GlAbstraction& glAbstraction, GlSyncAbstraction& glSyncAbstraction,
83             GestureManager& gestureManager, ResourcePolicy::DataRetention dataRetentionPolicy)
84 : mRenderController( renderController ),
85   mPlatform(platform),
86   mIsActive(true),
87   mProcessingEvent(false)
88 {
89   // Create the thread local storage
90   CreateThreadLocalStorage();
91
92   // This does nothing until Core is built with --enable-performance-monitor
93   PERFORMANCE_MONITOR_INIT( platform );
94
95   mNotificationManager = new NotificationManager();
96
97   mAnimationPlaylist = AnimationPlaylist::New();
98
99   mPropertyNotificationManager = PropertyNotificationManager::New();
100
101   mRenderTaskProcessor = new SceneGraph::RenderTaskProcessor();
102
103   mRenderManager = RenderManager::New( glAbstraction, glSyncAbstraction );
104
105   RenderQueue& renderQueue = mRenderManager->GetRenderQueue();
106
107   mDiscardQueue = new DiscardQueue( renderQueue );
108
109   mUpdateManager = new UpdateManager( *mNotificationManager,
110                                       *mAnimationPlaylist,
111                                       *mPropertyNotificationManager,
112                                       *mDiscardQueue,
113                                        renderController,
114                                       *mRenderManager,
115                                        renderQueue,
116                                       *mRenderTaskProcessor );
117
118   mRenderManager->SetShaderSaver( *mUpdateManager );
119
120   mStage = IntrusivePtr<Stage>( Stage::New( *mAnimationPlaylist, *mPropertyNotificationManager, *mUpdateManager, *mNotificationManager ) );
121
122   // This must be called after stage is created but before stage initialization
123   mRelayoutController = IntrusivePtr< RelayoutController >( new RelayoutController( mRenderController ) );
124
125   mStage->Initialize();
126
127   mGestureEventProcessor = new GestureEventProcessor(*mStage, gestureManager, mRenderController);
128   mEventProcessor = new EventProcessor(*mStage, *mNotificationManager, *mGestureEventProcessor);
129
130   mShaderFactory = new ShaderFactory();
131   mUpdateManager->SetShaderSaver( *mShaderFactory );
132
133   GetImplementation(Dali::TypeRegistry::Get()).CallInitFunctions();
134 }
135
136 Core::~Core()
137 {
138   /*
139    * The order of destructing these singletons is important!!!
140    */
141
142   // clear the thread local storage first
143   // allows core to be created / deleted many times in the same thread (how TET cases work).
144   // Do this before mStage.Reset() so Stage::IsInstalled() returns false
145   ThreadLocalStorage* tls = ThreadLocalStorage::GetInternal();
146   if( tls )
147   {
148     tls->Remove();
149     delete tls;
150   }
151
152   // Stop relayout requests being raised on stage destruction
153   mRelayoutController.Reset();
154
155   // Clean-up stage - remove default camera and root layer
156   mStage->Uninitialize();
157
158   // remove (last?) reference to stage
159   mStage.Reset();
160
161 }
162
163 Integration::ContextNotifierInterface* Core::GetContextNotifier()
164 {
165   return mStage.Get();
166 }
167
168 void Core::RecoverFromContextLoss()
169 {
170   DALI_LOG_INFO(gCoreFilter, Debug::Verbose, "Core::RecoverFromContextLoss()\n");
171
172   mStage->GetRenderTaskList().RecoverFromContextLoss(); // Re-trigger render-tasks
173 }
174
175 void Core::ContextCreated()
176 {
177   mRenderManager->ContextCreated();
178 }
179
180 void Core::ContextDestroyed()
181 {
182   mRenderManager->ContextDestroyed();
183 }
184
185 void Core::SurfaceResized( unsigned int width, unsigned int height )
186 {
187   mStage->SurfaceResized( width, height );
188
189   // The stage-size may be less than surface-size (reduced by top-margin)
190   Vector2 size = mStage->GetSize();
191   mRelayoutController->SetStageSize( size.width, size.height );
192 }
193
194 void Core::SetTopMargin( unsigned int margin )
195 {
196   mStage->SetTopMargin( margin );
197
198   // The stage-size may be less than surface-size (reduced by top-margin)
199   Vector2 size = mStage->GetSize();
200   mRelayoutController->SetStageSize( size.width, size.height );
201 }
202
203 void Core::SetDpi( unsigned int dpiHorizontal, unsigned int dpiVertical )
204 {
205   mStage->SetDpi( Vector2( dpiHorizontal , dpiVertical) );
206 }
207
208 void Core::Update( float elapsedSeconds, unsigned int lastVSyncTimeMilliseconds, unsigned int nextVSyncTimeMilliseconds, Integration::UpdateStatus& status )
209 {
210   // set the time delta so adaptor can easily print FPS with a release build with 0 as
211   // it is cached by frametime
212   status.secondsFromLastFrame = elapsedSeconds;
213
214   // Render returns true when there are updates on the stage or one or more animations are completed.
215   // Use the estimated time diff till we render as the elapsed time.
216   status.keepUpdating = mUpdateManager->Update( elapsedSeconds,
217                                                 lastVSyncTimeMilliseconds,
218                                                 nextVSyncTimeMilliseconds );
219
220   // Check the Notification Manager message queue to set needsNotification
221   status.needsNotification = mNotificationManager->MessagesToProcess();
222
223   // No need to keep update running if there are notifications to process.
224   // Any message to update will wake it up anyways
225 }
226
227 void Core::Render( RenderStatus& status )
228 {
229   bool updateRequired = mRenderManager->Render( status );
230
231   status.SetNeedsUpdate( updateRequired );
232 }
233
234 void Core::Suspend()
235 {
236   mIsActive = false;
237 }
238
239 void Core::Resume()
240 {
241   mIsActive = true;
242
243   // trigger processing of events queued up while paused
244   ProcessEvents();
245 }
246
247 void Core::SceneCreated()
248 {
249   mStage->EmitSceneCreatedSignal();
250
251   mRelayoutController->OnApplicationSceneCreated();
252 }
253
254 void Core::QueueEvent( const Integration::Event& event )
255 {
256   mEventProcessor->QueueEvent( event );
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();
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   mEventProcessor->ProcessEvents();
276
277   mNotificationManager->ProcessMessages();
278
279   // Avoid allocating MessageBuffers, triggering size-negotiation or sending any other spam whilst paused
280   if( mIsActive )
281   {
282     // Emit signal here to inform listeners that event processing has finished.
283     mStage->EmitEventProcessingFinishedSignal();
284
285     // Run the size negotiation after event processing finished signal
286     mRelayoutController->Relayout();
287
288     // Flush any queued messages for the update-thread
289     const bool messagesToProcess = mUpdateManager->FlushQueue();
290
291     // Check if the touch or gestures require updates.
292     const bool gestureNeedsUpdate = mGestureEventProcessor->NeedsUpdate();
293
294     if( messagesToProcess || gestureNeedsUpdate )
295     {
296       // tell the render controller to keep update thread running
297       mRenderController.RequestUpdate();
298     }
299   }
300
301   mRelayoutController->SetProcessingCoreEvents( false );
302
303   // ProcessEvents() may now be called again
304   mProcessingEvent = false;
305 }
306
307 unsigned int Core::GetMaximumUpdateCount() const
308 {
309   return MAXIMUM_UPDATE_COUNT;
310 }
311
312 Integration::SystemOverlay& Core::GetSystemOverlay()
313 {
314   return mStage->GetSystemOverlay();
315 }
316
317 void Core::SetViewMode( ViewMode viewMode )
318 {
319   mStage->SetViewMode( viewMode );
320 }
321
322 ViewMode Core::GetViewMode() const
323 {
324   return mStage->GetViewMode();
325 }
326
327 void Core::SetStereoBase( float stereoBase )
328 {
329   mStage->SetStereoBase( stereoBase );
330 }
331
332 float Core::GetStereoBase() const
333 {
334   return mStage->GetStereoBase();
335 }
336
337 StagePtr Core::GetCurrentStage()
338 {
339   return mStage.Get();
340 }
341
342 PlatformAbstraction& Core::GetPlatform()
343 {
344   return mPlatform;
345 }
346
347 UpdateManager& Core::GetUpdateManager()
348 {
349   return *(mUpdateManager);
350 }
351
352 RenderManager& Core::GetRenderManager()
353 {
354   return *(mRenderManager);
355 }
356
357 NotificationManager& Core::GetNotificationManager()
358 {
359   return *(mNotificationManager);
360 }
361
362 ShaderFactory& Core::GetShaderFactory()
363 {
364   return *(mShaderFactory);
365 }
366
367 GestureEventProcessor& Core::GetGestureEventProcessor()
368 {
369   return *(mGestureEventProcessor);
370 }
371
372 RelayoutController& Core::GetRelayoutController()
373 {
374   return *(mRelayoutController.Get());
375 }
376
377 void Core::CreateThreadLocalStorage()
378 {
379   // a pointer to the ThreadLocalStorage object will be stored in TLS
380   // The ThreadLocalStorage object should be deleted by the Core destructor
381   new ThreadLocalStorage(this);
382 }
383
384 } // namespace Internal
385
386 } // namespace Dali