Updated all code to new format
[platform/core/uifw/dali-core.git] / dali / internal / update / manager / update-manager.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/update/manager/update-manager.h>
20
21 // INTERNAL INCLUDES
22 #include <dali/integration-api/core.h>
23
24 #include <dali/internal/event/animation/animation-playlist.h>
25 #include <dali/internal/event/common/notification-manager.h>
26 #include <dali/internal/event/common/property-notifier.h>
27 #include <dali/internal/event/effects/shader-factory.h>
28
29 #include <dali/internal/update/common/discard-queue.h>
30 #include <dali/internal/update/controllers/render-message-dispatcher.h>
31 #include <dali/internal/update/controllers/scene-controller-impl.h>
32 #include <dali/internal/update/manager/frame-callback-processor.h>
33 #include <dali/internal/update/manager/render-task-processor.h>
34 #include <dali/internal/update/manager/transform-manager.h>
35 #include <dali/internal/update/manager/update-algorithms.h>
36 #include <dali/internal/update/manager/update-manager-debug.h>
37 #include <dali/internal/update/nodes/node.h>
38 #include <dali/internal/update/queue/update-message-queue.h>
39
40 #include <dali/internal/render/common/render-manager.h>
41 #include <dali/internal/render/queue/render-queue.h>
42
43 // Un-comment to enable node tree debug logging
44 //#define NODE_TREE_LOGGING 1
45
46 #if(defined(DEBUG_ENABLED) && defined(NODE_TREE_LOGGING))
47 #define SNAPSHOT_NODE_LOGGING                    \
48   const uint32_t FRAME_COUNT_TRIGGER = 16;       \
49   if(mImpl->frameCounter >= FRAME_COUNT_TRIGGER) \
50   {                                              \
51     for(auto&& scene : mImpl->scenes)
52 {
53   if(scene && scene->root)
54   {
55     mImpl->frameCounter = 0;
56     PrintNodeTree(*scene->root, mSceneGraphBuffers.GetUpdateBufferIndex(), "");
57   }
58 }
59 }
60 mImpl->frameCounter++;
61 #else
62 #define SNAPSHOT_NODE_LOGGING
63 #endif
64
65 #if defined(DEBUG_ENABLED)
66 extern Debug::Filter* gRenderTaskLogFilter;
67 namespace
68 {
69 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_UPDATE_MANAGER");
70 } // unnamed namespace
71 #endif
72
73 using namespace Dali::Integration;
74 using Dali::Internal::Update::MessageQueue;
75
76 namespace Dali
77 {
78 namespace Internal
79 {
80 namespace SceneGraph
81 {
82 namespace
83 {
84 /**
85  * Helper to Erase an object from OwnerContainer using discard queue
86  * @param container to remove from
87  * @param object to remove
88  * @param discardQueue to put the object to
89  * @param updateBufferIndex to use
90  */
91 template<class T>
92 inline void EraseUsingDiscardQueue(OwnerContainer<T*>& container, T* object, DiscardQueue& discardQueue, BufferIndex updateBufferIndex)
93 {
94   DALI_ASSERT_DEBUG(object && "NULL object not allowed");
95
96   // need to use the reference version of auto as we need the pointer to the pointer for the Release call below
97   for(auto&& iter : container)
98   {
99     if(iter == object)
100     {
101       // Transfer ownership to the discard queue, this keeps the object alive, until the render-thread has finished with it
102       discardQueue.Add(updateBufferIndex, container.Release(&iter)); // take the address of the reference to a pointer (iter)
103       return;                                                        // return as we only ever remove one object. Iterators to container are now invalidated as well so cannot continue
104     }
105   }
106 }
107
108 /**
109  * Descends into node's hierarchy and sorts the children of each child according to their depth-index.
110  * @param[in] node The node whose hierarchy to descend
111  */
112 void SortSiblingNodesRecursively(Node& node)
113 {
114   NodeContainer& container = node.GetChildren();
115   std::sort(container.Begin(), container.End(), [](Node* a, Node* b) { return a->GetDepthIndex() < b->GetDepthIndex(); });
116
117   // Descend tree and sort as well
118   for(auto&& iter : container)
119   {
120     SortSiblingNodesRecursively(*iter);
121   }
122 }
123
124 } // unnamed namespace
125
126 /**
127  * Structure to contain UpdateManager internal data
128  */
129 struct UpdateManager::Impl
130 {
131   // SceneInfo keeps the root node of the Scene, its scene graph render task list, and the list of Layer pointers sorted by depth
132   struct SceneInfo
133   {
134     SceneInfo(Layer* root) ///< Constructor
135     : root(root)
136     {
137     }
138
139     ~SceneInfo()               = default;                ///< Default non-virtual destructor
140     SceneInfo(SceneInfo&& rhs) = default;                ///< Move constructor
141     SceneInfo& operator=(SceneInfo&& rhs) = default;     ///< Move assignment operator
142     SceneInfo& operator=(const SceneInfo& rhs) = delete; ///< Assignment operator
143     SceneInfo(const SceneInfo& rhs)            = delete; ///< Copy constructor
144
145     Layer*                       root{nullptr};   ///< Root node (root is a layer). The layer is not stored in the node memory pool.
146     OwnerPointer<RenderTaskList> taskList;        ///< Scene graph render task list
147     SortedLayerPointers          sortedLayerList; ///< List of Layer pointers sorted by depth (one list of sorted layers per root)
148     OwnerPointer<Scene>          scene;           ///< Scene graph object of the scene
149   };
150
151   Impl(NotificationManager&           notificationManager,
152        CompleteNotificationInterface& animationPlaylist,
153        PropertyNotifier&              propertyNotifier,
154        DiscardQueue&                  discardQueue,
155        RenderController&              renderController,
156        RenderManager&                 renderManager,
157        RenderQueue&                   renderQueue,
158        SceneGraphBuffers&             sceneGraphBuffers,
159        RenderTaskProcessor&           renderTaskProcessor)
160   : renderMessageDispatcher(renderManager, renderQueue, sceneGraphBuffers),
161     notificationManager(notificationManager),
162     transformManager(),
163     animationPlaylist(animationPlaylist),
164     propertyNotifier(propertyNotifier),
165     shaderSaver(nullptr),
166     discardQueue(discardQueue),
167     renderController(renderController),
168     sceneController(nullptr),
169     renderManager(renderManager),
170     renderQueue(renderQueue),
171     renderTaskProcessor(renderTaskProcessor),
172     backgroundColor(Dali::DEFAULT_BACKGROUND_COLOR),
173     renderers(),
174     textureSets(),
175     shaders(),
176     panGestureProcessor(nullptr),
177     messageQueue(renderController, sceneGraphBuffers),
178     frameCallbackProcessor(nullptr),
179     keepRenderingSeconds(0.0f),
180     nodeDirtyFlags(NodePropertyFlags::TRANSFORM), // set to TransformFlag to ensure full update the first time through Update()
181     frameCounter(0),
182     renderingBehavior(DevelStage::Rendering::IF_REQUIRED),
183     animationFinishedDuringUpdate(false),
184     previousUpdateScene(false),
185     renderTaskWaiting(false),
186     renderersAdded(false),
187     renderingRequired(false)
188   {
189     sceneController = new SceneControllerImpl(renderMessageDispatcher, renderQueue, discardQueue);
190
191     // create first 'dummy' node
192     nodes.PushBack(nullptr);
193   }
194
195   ~Impl()
196   {
197     // Disconnect render tasks from nodes, before destroying the nodes
198     for(auto&& scene : scenes)
199     {
200       if(scene && scene->taskList)
201       {
202         RenderTaskList::RenderTaskContainer& tasks = scene->taskList->GetTasks();
203         for(auto&& task : tasks)
204         {
205           task->SetSourceNode(nullptr);
206         }
207       }
208     }
209
210     // UpdateManager owns the Nodes. Although Nodes are pool allocated they contain heap allocated parts
211     // like custom properties, which get released here
212     Vector<Node*>::Iterator iter    = nodes.Begin() + 1;
213     Vector<Node*>::Iterator endIter = nodes.End();
214     for(; iter != endIter; ++iter)
215     {
216       (*iter)->OnDestroy();
217       Node::Delete(*iter);
218     }
219
220     for(auto&& scene : scenes)
221     {
222       if(scene && scene->root)
223       {
224         scene->root->OnDestroy();
225         Node::Delete(scene->root);
226       }
227     }
228     scenes.clear();
229
230     delete sceneController;
231   }
232
233   /**
234    * Lazy init for FrameCallbackProcessor.
235    * @param[in]  updateManager  A reference to the update-manager
236    */
237   FrameCallbackProcessor& GetFrameCallbackProcessor(UpdateManager& updateManager)
238   {
239     if(!frameCallbackProcessor)
240     {
241       frameCallbackProcessor = new FrameCallbackProcessor(updateManager, transformManager);
242     }
243     return *frameCallbackProcessor;
244   }
245
246   SceneGraphBuffers              sceneGraphBuffers;       ///< Used to keep track of which buffers are being written or read
247   RenderMessageDispatcher        renderMessageDispatcher; ///< Used for passing messages to the render-thread
248   NotificationManager&           notificationManager;     ///< Queues notification messages for the event-thread.
249   TransformManager               transformManager;        ///< Used to update the transformation matrices of the nodes
250   CompleteNotificationInterface& animationPlaylist;       ///< Holds handles to all the animations
251   PropertyNotifier&              propertyNotifier;        ///< Provides notification to applications when properties are modified.
252   ShaderSaver*                   shaderSaver;             ///< Saves shader binaries.
253   DiscardQueue&                  discardQueue;            ///< Nodes are added here when disconnected from the scene-graph.
254   RenderController&              renderController;        ///< render controller
255   SceneControllerImpl*           sceneController;         ///< scene controller
256   RenderManager&                 renderManager;           ///< This is responsible for rendering the results of each "update"
257   RenderQueue&                   renderQueue;             ///< Used to queue messages for the next render
258   RenderTaskProcessor&           renderTaskProcessor;     ///< Handles RenderTasks and RenderInstrucitons
259
260   Vector4 backgroundColor; ///< The glClear color used at the beginning of each frame.
261
262   using SceneInfoPtr = std::unique_ptr<SceneInfo>;
263   std::vector<SceneInfoPtr> scenes; ///< A container of SceneInfo.
264
265   Vector<Node*> nodes; ///< A container of all instantiated nodes
266
267   OwnerContainer<Camera*>        cameras;       ///< A container of cameras
268   OwnerContainer<PropertyOwner*> customObjects; ///< A container of owned objects (with custom properties)
269
270   OwnerContainer<PropertyResetterBase*> propertyResetters;     ///< A container of property resetters
271   OwnerContainer<Animation*>            animations;            ///< A container of owned animations
272   PropertyNotificationContainer         propertyNotifications; ///< A container of owner property notifications.
273   OwnerContainer<Renderer*>             renderers;             ///< A container of owned renderers
274   OwnerContainer<TextureSet*>           textureSets;           ///< A container of owned texture sets
275   OwnerContainer<Shader*>               shaders;               ///< A container of owned shaders
276   OwnerPointer<PanGesture>              panGestureProcessor;   ///< Owned pan gesture processor; it lives for the lifecycle of UpdateManager
277
278   MessageQueue                         messageQueue;          ///< The messages queued from the event-thread
279   std::vector<Internal::ShaderDataPtr> renderCompiledShaders; ///< Shaders compiled on Render thread are inserted here for update thread to pass on to event thread.
280   std::vector<Internal::ShaderDataPtr> updateCompiledShaders; ///< Shaders to be sent from Update to Event
281   Mutex                                compiledShaderMutex;   ///< lock to ensure no corruption on the renderCompiledShaders
282
283   OwnerPointer<FrameCallbackProcessor> frameCallbackProcessor; ///< Owned FrameCallbackProcessor, only created if required.
284
285   float             keepRenderingSeconds; ///< Set via Dali::Stage::KeepRendering
286   NodePropertyFlags nodeDirtyFlags;       ///< cumulative node dirty flags from previous frame
287   uint32_t          frameCounter;         ///< Frame counter used in debugging to choose which frame to debug and which to ignore.
288
289   DevelStage::Rendering renderingBehavior; ///< Set via DevelStage::SetRenderingBehavior
290
291   bool animationFinishedDuringUpdate; ///< Flag whether any animations finished during the Update()
292   bool previousUpdateScene;           ///< True if the scene was updated in the previous frame (otherwise it was optimized out)
293   bool renderTaskWaiting;             ///< A REFRESH_ONCE render task is waiting to be rendered
294   bool renderersAdded;                ///< Flag to keep track when renderers have been added to avoid unnecessary processing
295   bool renderingRequired;             ///< True if required to render the current frame
296
297 private:
298   Impl(const Impl&);            ///< Undefined
299   Impl& operator=(const Impl&); ///< Undefined
300 };
301
302 UpdateManager::UpdateManager(NotificationManager&           notificationManager,
303                              CompleteNotificationInterface& animationFinishedNotifier,
304                              PropertyNotifier&              propertyNotifier,
305                              DiscardQueue&                  discardQueue,
306                              RenderController&              controller,
307                              RenderManager&                 renderManager,
308                              RenderQueue&                   renderQueue,
309                              RenderTaskProcessor&           renderTaskProcessor)
310 : mImpl(nullptr)
311 {
312   mImpl = new Impl(notificationManager,
313                    animationFinishedNotifier,
314                    propertyNotifier,
315                    discardQueue,
316                    controller,
317                    renderManager,
318                    renderQueue,
319                    mSceneGraphBuffers,
320                    renderTaskProcessor);
321 }
322
323 UpdateManager::~UpdateManager()
324 {
325   delete mImpl;
326 }
327
328 void UpdateManager::InstallRoot(OwnerPointer<Layer>& layer)
329 {
330   DALI_ASSERT_DEBUG(layer->IsLayer());
331   DALI_ASSERT_DEBUG(layer->GetParent() == NULL);
332
333   Layer* rootLayer = layer.Release();
334
335   DALI_ASSERT_DEBUG(std::find_if(mImpl->scenes.begin(), mImpl->scenes.end(), [rootLayer](Impl::SceneInfoPtr& scene) {
336                       return scene && scene->root == rootLayer;
337                     }) == mImpl->scenes.end() &&
338                     "Root Node already installed");
339
340   rootLayer->CreateTransform(&mImpl->transformManager);
341   rootLayer->SetRoot(true);
342
343   mImpl->scenes.emplace_back(new Impl::SceneInfo(rootLayer));
344 }
345
346 void UpdateManager::UninstallRoot(Layer* layer)
347 {
348   DALI_ASSERT_DEBUG(layer->IsLayer());
349   DALI_ASSERT_DEBUG(layer->GetParent() == NULL);
350
351   for(auto iter = mImpl->scenes.begin(); iter != mImpl->scenes.end(); ++iter)
352   {
353     if((*iter) && (*iter)->root == layer)
354     {
355       mImpl->scenes.erase(iter);
356       break;
357     }
358   }
359
360   mImpl->discardQueue.Add(mSceneGraphBuffers.GetUpdateBufferIndex(), layer);
361
362   // Notify the layer about impending destruction
363   layer->OnDestroy();
364 }
365
366 void UpdateManager::AddNode(OwnerPointer<Node>& node)
367 {
368   DALI_ASSERT_ALWAYS(nullptr == node->GetParent()); // Should not have a parent yet
369
370   Node* rawNode = node.Release();
371   DALI_LOG_INFO(gLogFilter, Debug::General, "[%x] AddNode\n", rawNode);
372
373   mImpl->nodes.PushBack(rawNode);
374   rawNode->CreateTransform(&mImpl->transformManager);
375 }
376
377 void UpdateManager::ConnectNode(Node* parent, Node* node)
378 {
379   DALI_ASSERT_ALWAYS(nullptr != parent);
380   DALI_ASSERT_ALWAYS(nullptr != node);
381   DALI_ASSERT_ALWAYS(nullptr == node->GetParent()); // Should not have a parent yet
382
383   DALI_LOG_INFO(gLogFilter, Debug::General, "[%x] ConnectNode\n", node);
384
385   parent->ConnectChild(node);
386
387   // Inform the frame-callback-processor, if set, about the node-hierarchy changing
388   if(mImpl->frameCallbackProcessor)
389   {
390     mImpl->frameCallbackProcessor->NodeHierarchyChanged();
391   }
392 }
393
394 void UpdateManager::DisconnectNode(Node* node)
395 {
396   DALI_LOG_INFO(gLogFilter, Debug::General, "[%x] DisconnectNode\n", node);
397
398   Node* parent = node->GetParent();
399   DALI_ASSERT_ALWAYS(nullptr != parent);
400   parent->SetDirtyFlag(NodePropertyFlags::CHILD_DELETED); // make parent dirty so that render items dont get reused
401
402   parent->DisconnectChild(mSceneGraphBuffers.GetUpdateBufferIndex(), *node);
403
404   // Inform the frame-callback-processor, if set, about the node-hierarchy changing
405   if(mImpl->frameCallbackProcessor)
406   {
407     mImpl->frameCallbackProcessor->NodeHierarchyChanged();
408   }
409 }
410
411 void UpdateManager::DestroyNode(Node* node)
412 {
413   DALI_ASSERT_ALWAYS(nullptr != node);
414   DALI_ASSERT_ALWAYS(nullptr == node->GetParent()); // Should have been disconnected
415
416   DALI_LOG_INFO(gLogFilter, Debug::General, "[%x] DestroyNode\n", node);
417
418   Vector<Node*>::Iterator iter    = mImpl->nodes.Begin() + 1;
419   Vector<Node*>::Iterator endIter = mImpl->nodes.End();
420   for(; iter != endIter; ++iter)
421   {
422     if((*iter) == node)
423     {
424       mImpl->nodes.Erase(iter);
425       break;
426     }
427   }
428
429   mImpl->discardQueue.Add(mSceneGraphBuffers.GetUpdateBufferIndex(), node);
430
431   // Notify the Node about impending destruction
432   node->OnDestroy();
433 }
434
435 void UpdateManager::AddCamera(OwnerPointer<Camera>& camera)
436 {
437   mImpl->cameras.PushBack(camera.Release()); // takes ownership
438 }
439
440 void UpdateManager::RemoveCamera(Camera* camera)
441 {
442   // Find the camera and destroy it
443   EraseUsingDiscardQueue(mImpl->cameras, camera, mImpl->discardQueue, mSceneGraphBuffers.GetUpdateBufferIndex());
444 }
445
446 void UpdateManager::AddObject(OwnerPointer<PropertyOwner>& object)
447 {
448   mImpl->customObjects.PushBack(object.Release());
449 }
450
451 void UpdateManager::RemoveObject(PropertyOwner* object)
452 {
453   mImpl->customObjects.EraseObject(object);
454 }
455
456 void UpdateManager::AddRenderTaskList(OwnerPointer<RenderTaskList>& taskList)
457 {
458   RenderTaskList* taskListPointer = taskList.Release();
459   taskListPointer->SetRenderMessageDispatcher(&mImpl->renderMessageDispatcher);
460
461   mImpl->scenes.back()->taskList = taskListPointer;
462 }
463
464 void UpdateManager::RemoveRenderTaskList(RenderTaskList* taskList)
465 {
466   for(auto&& scene : mImpl->scenes)
467   {
468     if(scene && scene->taskList == taskList)
469     {
470       scene->taskList.Reset();
471       break;
472     }
473   }
474 }
475
476 void UpdateManager::AddScene(OwnerPointer<Scene>& scene)
477 {
478   mImpl->scenes.back()->scene = scene.Release();
479
480   // Initialize the context from render manager
481   typedef MessageValue1<RenderManager, SceneGraph::Scene*> DerivedType;
482
483   // Reserve some memory inside the render queue
484   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
485
486   // Construct message in the render queue memory; note that delete should not be called on the return value
487   SceneGraph::Scene& sceneObject = *mImpl->scenes.back()->scene;
488   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::InitializeScene, &sceneObject);
489 }
490
491 void UpdateManager::RemoveScene(Scene* scene)
492 {
493   // Initialize the context from render manager
494   using DerivedType = MessageValue1<RenderManager, SceneGraph::Scene*>;
495
496   // Reserve some memory inside the render queue
497   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
498
499   // Construct message in the render queue memory; note that delete should not be called on the return value
500   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::UninitializeScene, scene);
501
502   for(auto&& sceneInfo : mImpl->scenes)
503   {
504     if(sceneInfo && sceneInfo->scene && sceneInfo->scene.Get() == scene)
505     {
506       mImpl->discardQueue.Add(mSceneGraphBuffers.GetUpdateBufferIndex(), sceneInfo->scene.Release()); // take the address of the reference to a pointer
507       break;
508     }
509   }
510 }
511
512 void UpdateManager::AddAnimation(OwnerPointer<SceneGraph::Animation>& animation)
513 {
514   mImpl->animations.PushBack(animation.Release());
515 }
516
517 void UpdateManager::StopAnimation(Animation* animation)
518 {
519   DALI_ASSERT_DEBUG(animation && "NULL animation called to stop");
520
521   bool animationFinished = animation->Stop(mSceneGraphBuffers.GetUpdateBufferIndex());
522
523   mImpl->animationFinishedDuringUpdate = mImpl->animationFinishedDuringUpdate || animationFinished;
524 }
525
526 void UpdateManager::RemoveAnimation(Animation* animation)
527 {
528   DALI_ASSERT_DEBUG(animation && "NULL animation called to remove");
529
530   animation->OnDestroy(mSceneGraphBuffers.GetUpdateBufferIndex());
531
532   DALI_ASSERT_DEBUG(animation->GetState() == Animation::Destroyed);
533 }
534
535 bool UpdateManager::IsAnimationRunning() const
536 {
537   // Find any animation that isn't stopped or paused
538   for(auto&& iter : mImpl->animations)
539   {
540     const Animation::State state = iter->GetState();
541
542     if(state != Animation::Stopped &&
543        state != Animation::Paused)
544     {
545       return true; // stop iteration as soon as first one is found
546     }
547   }
548
549   return false;
550 }
551
552 void UpdateManager::AddPropertyResetter(OwnerPointer<PropertyResetterBase>& propertyResetter)
553 {
554   propertyResetter->Initialize();
555   mImpl->propertyResetters.PushBack(propertyResetter.Release());
556 }
557
558 void UpdateManager::AddPropertyNotification(OwnerPointer<PropertyNotification>& propertyNotification)
559 {
560   mImpl->propertyNotifications.PushBack(propertyNotification.Release());
561 }
562
563 void UpdateManager::RemovePropertyNotification(PropertyNotification* propertyNotification)
564 {
565   mImpl->propertyNotifications.EraseObject(propertyNotification);
566 }
567
568 void UpdateManager::PropertyNotificationSetNotify(PropertyNotification* propertyNotification, PropertyNotification::NotifyMode notifyMode)
569 {
570   DALI_ASSERT_DEBUG(propertyNotification && "propertyNotification scene graph object missing");
571   propertyNotification->SetNotifyMode(notifyMode);
572 }
573
574 void UpdateManager::AddShader(OwnerPointer<Shader>& shader)
575 {
576   mImpl->shaders.PushBack(shader.Release());
577 }
578
579 void UpdateManager::RemoveShader(Shader* shader)
580 {
581   // Find the shader and destroy it
582   EraseUsingDiscardQueue(mImpl->shaders, shader, mImpl->discardQueue, mSceneGraphBuffers.GetUpdateBufferIndex());
583 }
584
585 void UpdateManager::SetShaderProgram(Shader*                 shader,
586                                      Internal::ShaderDataPtr shaderData,
587                                      bool                    modifiesGeometry)
588 {
589   if(shaderData)
590   {
591     using DerivedType = MessageValue3<Shader, Internal::ShaderDataPtr, ProgramCache*, bool>;
592
593     // Reserve some memory inside the render queue
594     uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
595
596     // Construct message in the render queue memory; note that delete should not be called on the return value
597     new(slot) DerivedType(shader, &Shader::SetProgram, shaderData, mImpl->renderManager.GetProgramCache(), modifiesGeometry);
598   }
599 }
600
601 void UpdateManager::SaveBinary(Internal::ShaderDataPtr shaderData)
602 {
603   DALI_ASSERT_DEBUG(shaderData && "No NULL shader data pointers please.");
604   DALI_ASSERT_DEBUG(shaderData->GetBufferSize() > 0 && "Shader binary empty so nothing to save.");
605   {
606     // lock as update might be sending previously compiled shaders to event thread
607     Mutex::ScopedLock lock(mImpl->compiledShaderMutex);
608     mImpl->renderCompiledShaders.push_back(shaderData);
609   }
610 }
611
612 void UpdateManager::SetShaderSaver(ShaderSaver& upstream)
613 {
614   mImpl->shaderSaver = &upstream;
615 }
616
617 void UpdateManager::AddRenderer(OwnerPointer<Renderer>& renderer)
618 {
619   DALI_LOG_INFO(gLogFilter, Debug::General, "[%x] AddRenderer\n", renderer.Get());
620
621   renderer->ConnectToSceneGraph(*mImpl->sceneController, mSceneGraphBuffers.GetUpdateBufferIndex());
622   mImpl->renderers.PushBack(renderer.Release());
623   mImpl->renderersAdded = true;
624 }
625
626 void UpdateManager::RemoveRenderer(Renderer* renderer)
627 {
628   DALI_LOG_INFO(gLogFilter, Debug::General, "[%x] RemoveRenderer\n", renderer);
629
630   // Find the renderer and destroy it
631   EraseUsingDiscardQueue(mImpl->renderers, renderer, mImpl->discardQueue, mSceneGraphBuffers.GetUpdateBufferIndex());
632   // Need to remove the render object as well
633   renderer->DisconnectFromSceneGraph(*mImpl->sceneController, mSceneGraphBuffers.GetUpdateBufferIndex());
634 }
635
636 void UpdateManager::SetPanGestureProcessor(PanGesture* panGestureProcessor)
637 {
638   DALI_ASSERT_DEBUG(NULL != panGestureProcessor);
639
640   mImpl->panGestureProcessor = panGestureProcessor;
641 }
642
643 void UpdateManager::AddTextureSet(OwnerPointer<TextureSet>& textureSet)
644 {
645   mImpl->textureSets.PushBack(textureSet.Release());
646 }
647
648 void UpdateManager::RemoveTextureSet(TextureSet* textureSet)
649 {
650   mImpl->textureSets.EraseObject(textureSet);
651 }
652
653 uint32_t* UpdateManager::ReserveMessageSlot(uint32_t size, bool updateScene)
654 {
655   return mImpl->messageQueue.ReserveMessageSlot(size, updateScene);
656 }
657
658 void UpdateManager::EventProcessingStarted()
659 {
660   mImpl->messageQueue.EventProcessingStarted();
661 }
662
663 bool UpdateManager::FlushQueue()
664 {
665   return mImpl->messageQueue.FlushQueue();
666 }
667
668 void UpdateManager::ResetProperties(BufferIndex bufferIndex)
669 {
670   // Clear the "animations finished" flag; This should be set if any (previously playing) animation is stopped
671   mImpl->animationFinishedDuringUpdate = false;
672
673   // Reset all animating / constrained properties
674   std::vector<PropertyResetterBase*> toDelete;
675   for(auto&& element : mImpl->propertyResetters)
676   {
677     element->ResetToBaseValue(bufferIndex);
678     if(element->IsFinished())
679     {
680       toDelete.push_back(element);
681     }
682   }
683
684   // If a resetter is no longer required (the animator or constraint has been removed), delete it.
685   for(auto&& elementPtr : toDelete)
686   {
687     mImpl->propertyResetters.EraseObject(elementPtr);
688   }
689
690   // Clear all root nodes dirty flags
691   for(auto& scene : mImpl->scenes)
692   {
693     auto root = scene->root;
694     root->ResetDirtyFlags(bufferIndex);
695   }
696
697   // Clear node dirty flags
698   Vector<Node*>::Iterator iter    = mImpl->nodes.Begin() + 1;
699   Vector<Node*>::Iterator endIter = mImpl->nodes.End();
700   for(; iter != endIter; ++iter)
701   {
702     (*iter)->ResetDirtyFlags(bufferIndex);
703   }
704 }
705
706 bool UpdateManager::ProcessGestures(BufferIndex bufferIndex, uint32_t lastVSyncTimeMilliseconds, uint32_t nextVSyncTimeMilliseconds)
707 {
708   bool gestureUpdated(false);
709
710   if(mImpl->panGestureProcessor)
711   {
712     // gesture processor only supports default properties
713     mImpl->panGestureProcessor->ResetDefaultProperties(bufferIndex); // Needs to be done every time as gesture data is written directly to an update-buffer rather than via a message
714     gestureUpdated |= mImpl->panGestureProcessor->UpdateProperties(lastVSyncTimeMilliseconds, nextVSyncTimeMilliseconds);
715   }
716
717   return gestureUpdated;
718 }
719
720 bool UpdateManager::Animate(BufferIndex bufferIndex, float elapsedSeconds)
721 {
722   bool animationActive = false;
723
724   auto&& iter            = mImpl->animations.Begin();
725   bool   animationLooped = false;
726
727   while(iter != mImpl->animations.End())
728   {
729     Animation* animation             = *iter;
730     bool       finished              = false;
731     bool       looped                = false;
732     bool       progressMarkerReached = false;
733     animation->Update(bufferIndex, elapsedSeconds, looped, finished, progressMarkerReached);
734
735     animationActive = animationActive || animation->IsActive();
736
737     if(progressMarkerReached)
738     {
739       mImpl->notificationManager.QueueMessage(Internal::NotifyProgressReachedMessage(mImpl->animationPlaylist, animation));
740     }
741
742     mImpl->animationFinishedDuringUpdate = mImpl->animationFinishedDuringUpdate || finished;
743     animationLooped                      = animationLooped || looped;
744
745     // Remove animations that had been destroyed but were still waiting for an update
746     if(animation->GetState() == Animation::Destroyed)
747     {
748       iter = mImpl->animations.Erase(iter);
749     }
750     else
751     {
752       ++iter;
753     }
754   }
755
756   // queue the notification on finished or looped (to update loop count)
757   if(mImpl->animationFinishedDuringUpdate || animationLooped)
758   {
759     // The application should be notified by NotificationManager, in another thread
760     mImpl->notificationManager.QueueCompleteNotification(&mImpl->animationPlaylist);
761   }
762
763   return animationActive;
764 }
765
766 void UpdateManager::ConstrainCustomObjects(BufferIndex bufferIndex)
767 {
768   //Constrain custom objects (in construction order)
769   for(auto&& object : mImpl->customObjects)
770   {
771     ConstrainPropertyOwner(*object, bufferIndex);
772   }
773 }
774
775 void UpdateManager::ConstrainRenderTasks(BufferIndex bufferIndex)
776 {
777   // Constrain render-tasks
778   for(auto&& scene : mImpl->scenes)
779   {
780     if(scene && scene->taskList)
781     {
782       RenderTaskList::RenderTaskContainer& tasks = scene->taskList->GetTasks();
783       for(auto&& task : tasks)
784       {
785         ConstrainPropertyOwner(*task, bufferIndex);
786       }
787     }
788   }
789 }
790
791 void UpdateManager::ConstrainShaders(BufferIndex bufferIndex)
792 {
793   // constrain shaders... (in construction order)
794   for(auto&& shader : mImpl->shaders)
795   {
796     ConstrainPropertyOwner(*shader, bufferIndex);
797   }
798 }
799
800 void UpdateManager::ProcessPropertyNotifications(BufferIndex bufferIndex)
801 {
802   for(auto&& notification : mImpl->propertyNotifications)
803   {
804     bool valid = notification->Check(bufferIndex);
805     if(valid)
806     {
807       mImpl->notificationManager.QueueMessage(PropertyChangedMessage(mImpl->propertyNotifier, notification, notification->GetValidity()));
808     }
809   }
810 }
811
812 void UpdateManager::ForwardCompiledShadersToEventThread()
813 {
814   DALI_ASSERT_DEBUG((mImpl->shaderSaver != 0) && "shaderSaver should be wired-up during startup.");
815   if(mImpl->shaderSaver)
816   {
817     // lock and swap the queues
818     {
819       // render might be attempting to send us more binaries at the same time
820       Mutex::ScopedLock lock(mImpl->compiledShaderMutex);
821       mImpl->renderCompiledShaders.swap(mImpl->updateCompiledShaders);
822     }
823
824     if(mImpl->updateCompiledShaders.size() > 0)
825     {
826       ShaderSaver& factory = *mImpl->shaderSaver;
827       for(auto&& shader : mImpl->updateCompiledShaders)
828       {
829         mImpl->notificationManager.QueueMessage(ShaderCompiledMessage(factory, shader));
830       }
831       // we don't need them in update anymore
832       mImpl->updateCompiledShaders.clear();
833     }
834   }
835 }
836
837 void UpdateManager::UpdateRenderers(BufferIndex bufferIndex)
838 {
839   for(auto&& renderer : mImpl->renderers)
840   {
841     //Apply constraints
842     ConstrainPropertyOwner(*renderer, bufferIndex);
843
844     mImpl->renderingRequired = renderer->PrepareRender(bufferIndex) || mImpl->renderingRequired;
845   }
846 }
847
848 void UpdateManager::UpdateNodes(BufferIndex bufferIndex)
849 {
850   mImpl->nodeDirtyFlags = NodePropertyFlags::NOTHING;
851
852   for(auto&& scene : mImpl->scenes)
853   {
854     if(scene && scene->root)
855     {
856       // Prepare resources, update shaders, for each node
857       // And add the renderers to the sorted layers. Start from root, which is also a layer
858       mImpl->nodeDirtyFlags |= UpdateNodeTree(*scene->root,
859                                               bufferIndex,
860                                               mImpl->renderQueue);
861     }
862   }
863 }
864
865 uint32_t UpdateManager::Update(float    elapsedSeconds,
866                                uint32_t lastVSyncTimeMilliseconds,
867                                uint32_t nextVSyncTimeMilliseconds,
868                                bool     renderToFboEnabled,
869                                bool     isRenderingToFbo)
870 {
871   const BufferIndex bufferIndex = mSceneGraphBuffers.GetUpdateBufferIndex();
872
873   //Clear nodes/resources which were previously discarded
874   mImpl->discardQueue.Clear(bufferIndex);
875
876   bool isAnimationRunning = IsAnimationRunning();
877
878   //Process Touches & Gestures
879   const bool gestureUpdated = ProcessGestures(bufferIndex, lastVSyncTimeMilliseconds, nextVSyncTimeMilliseconds);
880
881   bool updateScene =                                   // The scene-graph requires an update if..
882     (mImpl->nodeDirtyFlags & RenderableUpdateFlags) || // ..nodes were dirty in previous frame OR
883     isAnimationRunning ||                              // ..at least one animation is running OR
884     mImpl->messageQueue.IsSceneUpdateRequired() ||     // ..a message that modifies the scene graph node tree is queued OR
885     mImpl->frameCallbackProcessor ||                   // ..a frame callback processor is existed OR
886     gestureUpdated;                                    // ..a gesture property was updated
887
888   bool keepRendererRendering = false;
889   mImpl->renderingRequired   = false;
890
891   // Although the scene-graph may not require an update, we still need to synchronize double-buffered
892   // values if the scene was updated in the previous frame.
893   if(updateScene || mImpl->previousUpdateScene)
894   {
895     //Reset properties from the previous update
896     ResetProperties(bufferIndex);
897     mImpl->transformManager.ResetToBaseValue();
898   }
899
900   // Process the queued scene messages. Note, MessageQueue::FlushQueue may be called
901   // between calling IsSceneUpdateRequired() above and here, so updateScene should
902   // be set again
903   updateScene |= mImpl->messageQueue.ProcessMessages(bufferIndex);
904
905   //Forward compiled shader programs to event thread for saving
906   ForwardCompiledShadersToEventThread();
907
908   // Although the scene-graph may not require an update, we still need to synchronize double-buffered
909   // renderer lists if the scene was updated in the previous frame.
910   // We should not start skipping update steps or reusing lists until there has been two frames where nothing changes
911   if(updateScene || mImpl->previousUpdateScene)
912   {
913     //Animate
914     bool animationActive = Animate(bufferIndex, elapsedSeconds);
915
916     //Constraint custom objects
917     ConstrainCustomObjects(bufferIndex);
918
919     //Clear the lists of renderers from the previous update
920     for(auto&& scene : mImpl->scenes)
921     {
922       if(scene)
923       {
924         for(auto&& layer : scene->sortedLayerList)
925         {
926           if(layer)
927           {
928             layer->ClearRenderables();
929           }
930         }
931       }
932     }
933
934     // Call the frame-callback-processor if set
935     if(mImpl->frameCallbackProcessor)
936     {
937       mImpl->frameCallbackProcessor->Update(bufferIndex, elapsedSeconds);
938     }
939
940     //Update node hierarchy, apply constraints and perform sorting / culling.
941     //This will populate each Layer with a list of renderers which are ready.
942     UpdateNodes(bufferIndex);
943
944     //Apply constraints to RenderTasks, shaders
945     ConstrainRenderTasks(bufferIndex);
946     ConstrainShaders(bufferIndex);
947
948     //Update renderers and apply constraints
949     UpdateRenderers(bufferIndex);
950
951     //Update the transformations of all the nodes
952     if(mImpl->transformManager.Update())
953     {
954       mImpl->nodeDirtyFlags |= NodePropertyFlags::TRANSFORM;
955     }
956
957     //Process Property Notifications
958     ProcessPropertyNotifications(bufferIndex);
959
960     //Update cameras
961     for(auto&& cameraIterator : mImpl->cameras)
962     {
963       cameraIterator->Update(bufferIndex);
964     }
965
966     //Process the RenderTasks if renderers exist. This creates the instructions for rendering the next frame.
967     //reset the update buffer index and make sure there is enough room in the instruction container
968     if(mImpl->renderersAdded)
969     {
970       // Calculate how many render tasks we have in total
971       std::size_t numberOfRenderTasks = 0;
972       for(auto&& scene : mImpl->scenes)
973       {
974         if(scene && scene->taskList)
975         {
976           numberOfRenderTasks += scene->taskList->GetTasks().Count();
977         }
978       }
979
980       std::size_t numberOfRenderInstructions = 0;
981       for(auto&& scene : mImpl->scenes)
982       {
983         if(scene && scene->root && scene->taskList && scene->scene)
984         {
985           scene->scene->GetRenderInstructions().ResetAndReserve(bufferIndex,
986                                                                 static_cast<uint32_t>(scene->taskList->GetTasks().Count()));
987
988           // If there are animations running, only add render instruction if at least one animation is currently active (i.e. not delayed)
989           // or the nodes are dirty
990           if(!isAnimationRunning || animationActive || mImpl->renderingRequired || (mImpl->nodeDirtyFlags & RenderableUpdateFlags))
991           {
992             keepRendererRendering |= mImpl->renderTaskProcessor.Process(bufferIndex,
993                                                                         *scene->taskList,
994                                                                         *scene->root,
995                                                                         scene->sortedLayerList,
996                                                                         scene->scene->GetRenderInstructions(),
997                                                                         renderToFboEnabled,
998                                                                         isRenderingToFbo);
999
1000             scene->scene->SetSkipRendering(false);
1001           }
1002           else
1003           {
1004             scene->scene->SetSkipRendering(true);
1005           }
1006
1007           numberOfRenderInstructions += scene->scene->GetRenderInstructions().Count(bufferIndex);
1008         }
1009       }
1010
1011       DALI_LOG_INFO(gLogFilter, Debug::General, "Update: numberOfRenderTasks(%d), Render Instructions(%d)\n", numberOfRenderTasks, numberOfRenderInstructions);
1012     }
1013   }
1014
1015   for(auto&& scene : mImpl->scenes)
1016   {
1017     if(scene && scene->root && scene->taskList)
1018     {
1019       RenderTaskList::RenderTaskContainer& tasks = scene->taskList->GetTasks();
1020
1021       // check the countdown and notify
1022       bool doRenderOnceNotify  = false;
1023       mImpl->renderTaskWaiting = false;
1024       for(auto&& renderTask : tasks)
1025       {
1026         renderTask->UpdateState();
1027
1028         if(renderTask->IsWaitingToRender() &&
1029            renderTask->ReadyToRender(bufferIndex) /*avoid updating forever when source actor is off-stage*/)
1030         {
1031           mImpl->renderTaskWaiting = true; // keep update/render threads alive
1032         }
1033
1034         if(renderTask->HasRendered())
1035         {
1036           doRenderOnceNotify = true;
1037         }
1038       }
1039
1040       if(doRenderOnceNotify)
1041       {
1042         DALI_LOG_INFO(gRenderTaskLogFilter, Debug::General, "Notify a render task has finished\n");
1043         mImpl->notificationManager.QueueCompleteNotification(scene->taskList->GetCompleteNotificationInterface());
1044       }
1045     }
1046   }
1047
1048   // Macro is undefined in release build.
1049   SNAPSHOT_NODE_LOGGING;
1050
1051   // A ResetProperties() may be required in the next frame
1052   mImpl->previousUpdateScene = updateScene;
1053
1054   // Check whether further updates are required
1055   uint32_t keepUpdating = KeepUpdatingCheck(elapsedSeconds);
1056
1057   if(keepRendererRendering)
1058   {
1059     keepUpdating |= KeepUpdating::STAGE_KEEP_RENDERING;
1060
1061     // Set dirty flags for next frame to continue rendering
1062     mImpl->nodeDirtyFlags |= RenderableUpdateFlags;
1063   }
1064
1065   // tell the update manager that we're done so the queue can be given to event thread
1066   mImpl->notificationManager.UpdateCompleted();
1067
1068   // The update has finished; swap the double-buffering indices
1069   mSceneGraphBuffers.Swap();
1070
1071   return keepUpdating;
1072 }
1073
1074 uint32_t UpdateManager::KeepUpdatingCheck(float elapsedSeconds) const
1075 {
1076   // Update the duration set via Stage::KeepRendering()
1077   if(mImpl->keepRenderingSeconds > 0.0f)
1078   {
1079     mImpl->keepRenderingSeconds -= elapsedSeconds;
1080   }
1081
1082   uint32_t keepUpdatingRequest = KeepUpdating::NOT_REQUESTED;
1083
1084   // If the rendering behavior is set to continuously render, then continue to render.
1085   // If Stage::KeepRendering() has been called, then continue until the duration has elapsed.
1086   // Keep updating until no messages are received and no animations are running.
1087   // If an animation has just finished, update at least once more for Discard end-actions.
1088   // No need to check for renderQueue as there is always a render after update and if that
1089   // render needs another update it will tell the adaptor to call update again
1090
1091   if((mImpl->renderingBehavior == DevelStage::Rendering::CONTINUOUSLY) ||
1092      (mImpl->keepRenderingSeconds > 0.0f))
1093   {
1094     keepUpdatingRequest |= KeepUpdating::STAGE_KEEP_RENDERING;
1095   }
1096
1097   if(IsAnimationRunning() ||
1098      mImpl->animationFinishedDuringUpdate)
1099   {
1100     keepUpdatingRequest |= KeepUpdating::ANIMATIONS_RUNNING;
1101   }
1102
1103   if(mImpl->renderTaskWaiting)
1104   {
1105     keepUpdatingRequest |= KeepUpdating::RENDER_TASK_SYNC;
1106   }
1107
1108   return keepUpdatingRequest;
1109 }
1110
1111 void UpdateManager::SurfaceReplaced(Scene* scene)
1112 {
1113   using DerivedType = MessageValue1<RenderManager, Scene*>;
1114
1115   // Reserve some memory inside the render queue
1116   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1117
1118   // Construct message in the render queue memory; note that delete should not be called on the return value
1119   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::SurfaceReplaced, scene);
1120 }
1121
1122 void UpdateManager::KeepRendering(float durationSeconds)
1123 {
1124   mImpl->keepRenderingSeconds = std::max(mImpl->keepRenderingSeconds, durationSeconds);
1125 }
1126
1127 void UpdateManager::SetRenderingBehavior(DevelStage::Rendering renderingBehavior)
1128 {
1129   mImpl->renderingBehavior = renderingBehavior;
1130 }
1131
1132 void UpdateManager::RequestRendering()
1133 {
1134   mImpl->renderingRequired = true;
1135 }
1136
1137 void UpdateManager::SetLayerDepths(const SortedLayerPointers& layers, const Layer* rootLayer)
1138 {
1139   for(auto&& scene : mImpl->scenes)
1140   {
1141     if(scene && scene->root == rootLayer)
1142     {
1143       scene->sortedLayerList = layers;
1144       break;
1145     }
1146   }
1147 }
1148
1149 void UpdateManager::SetDepthIndices(OwnerPointer<NodeDepths>& nodeDepths)
1150 {
1151   // note,this vector is already in depth order. It could be used as-is to
1152   // remove sorting in update algorithm. However, it lacks layer boundary markers.
1153   for(auto&& iter : nodeDepths->nodeDepths)
1154   {
1155     iter.node->SetDepthIndex(iter.sortedDepth);
1156   }
1157
1158   for(auto&& scene : mImpl->scenes)
1159   {
1160     if(scene)
1161     {
1162       // Go through node hierarchy and rearrange siblings according to depth-index
1163       SortSiblingNodesRecursively(*scene->root);
1164     }
1165   }
1166 }
1167
1168 void UpdateManager::AddFrameCallback(OwnerPointer<FrameCallback>& frameCallback, const Node* rootNode)
1169 {
1170   mImpl->GetFrameCallbackProcessor(*this).AddFrameCallback(frameCallback, rootNode);
1171 }
1172
1173 void UpdateManager::RemoveFrameCallback(FrameCallbackInterface* frameCallback)
1174 {
1175   mImpl->GetFrameCallbackProcessor(*this).RemoveFrameCallback(frameCallback);
1176 }
1177
1178 void UpdateManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
1179 {
1180   // Message has ownership of Sampler while in transit from update to render
1181   using DerivedType = MessageValue1<RenderManager, OwnerPointer<Render::Sampler> >;
1182
1183   // Reserve some memory inside the render queue
1184   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1185
1186   // Construct message in the render queue memory; note that delete should not be called on the return value
1187   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::AddSampler, sampler);
1188 }
1189
1190 void UpdateManager::RemoveSampler(Render::Sampler* sampler)
1191 {
1192   using DerivedType = MessageValue1<RenderManager, Render::Sampler*>;
1193
1194   // Reserve some memory inside the render queue
1195   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1196
1197   // Construct message in the render queue memory; note that delete should not be called on the return value
1198   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::RemoveSampler, sampler);
1199 }
1200
1201 void UpdateManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
1202 {
1203   using DerivedType = MessageValue3<RenderManager, Render::Sampler*, uint32_t, uint32_t>;
1204
1205   // Reserve some memory inside the render queue
1206   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1207
1208   // Construct message in the render queue memory; note that delete should not be called on the return value
1209   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::SetFilterMode, sampler, minFilterMode, magFilterMode);
1210 }
1211
1212 void UpdateManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
1213 {
1214   using DerivedType = MessageValue4<RenderManager, Render::Sampler*, uint32_t, uint32_t, uint32_t>;
1215
1216   // Reserve some memory inside the render queue
1217   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1218
1219   // Construct message in the render queue memory; note that delete should not be called on the return value
1220   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::SetWrapMode, sampler, rWrapMode, sWrapMode, tWrapMode);
1221 }
1222
1223 void UpdateManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
1224 {
1225   // Message has ownership of format while in transit from update -> render
1226   using DerivedType = MessageValue1<RenderManager, OwnerPointer<Render::VertexBuffer> >;
1227
1228   // Reserve some memory inside the render queue
1229   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1230
1231   // Construct message in the render queue memory; note that delete should not be called on the return value
1232   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::AddVertexBuffer, vertexBuffer);
1233 }
1234
1235 void UpdateManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
1236 {
1237   using DerivedType = MessageValue1<RenderManager, Render::VertexBuffer*>;
1238
1239   // Reserve some memory inside the render queue
1240   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1241
1242   // Construct message in the render queue memory; note that delete should not be called on the return value
1243   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::RemoveVertexBuffer, vertexBuffer);
1244 }
1245
1246 void UpdateManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
1247 {
1248   // Message has ownership of format while in transit from update -> render
1249   using DerivedType = MessageValue2<RenderManager, Render::VertexBuffer*, OwnerPointer<Render::VertexBuffer::Format> >;
1250
1251   // Reserve some memory inside the render queue
1252   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1253
1254   // Construct message in the render queue memory; note that delete should not be called on the return value
1255   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::SetVertexBufferFormat, vertexBuffer, format);
1256 }
1257
1258 void UpdateManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t> >& data, uint32_t size)
1259 {
1260   // Message has ownership of format while in transit from update -> render
1261   using DerivedType = MessageValue3<RenderManager, Render::VertexBuffer*, OwnerPointer<Dali::Vector<uint8_t> >, uint32_t>;
1262
1263   // Reserve some memory inside the render queue
1264   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1265
1266   // Construct message in the render queue memory; note that delete should not be called on the return value
1267   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::SetVertexBufferData, vertexBuffer, data, size);
1268 }
1269
1270 void UpdateManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
1271 {
1272   // Message has ownership of format while in transit from update -> render
1273   using DerivedType = MessageValue1<RenderManager, OwnerPointer<Render::Geometry> >;
1274
1275   // Reserve some memory inside the render queue
1276   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1277
1278   // Construct message in the render queue memory; note that delete should not be called on the return value
1279   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::AddGeometry, geometry);
1280 }
1281
1282 void UpdateManager::RemoveGeometry(Render::Geometry* geometry)
1283 {
1284   using DerivedType = MessageValue1<RenderManager, Render::Geometry*>;
1285
1286   // Reserve some memory inside the render queue
1287   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1288
1289   // Construct message in the render queue memory; note that delete should not be called on the return value
1290   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::RemoveGeometry, geometry);
1291 }
1292
1293 void UpdateManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
1294 {
1295   using DerivedType = MessageValue2<RenderManager, Render::Geometry*, uint32_t>;
1296
1297   // Reserve some memory inside the render queue
1298   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1299
1300   // Construct message in the render queue memory; note that delete should not be called on the return value
1301   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::SetGeometryType, geometry, geometryType);
1302 }
1303
1304 void UpdateManager::SetIndexBuffer(Render::Geometry* geometry, Dali::Vector<uint16_t>& indices)
1305 {
1306   using DerivedType = IndexBufferMessage<RenderManager>;
1307
1308   // Reserve some memory inside the render queue
1309   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1310
1311   // Construct message in the render queue memory; note that delete should not be called on the return value
1312   new(slot) DerivedType(&mImpl->renderManager, geometry, indices);
1313 }
1314
1315 void UpdateManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
1316 {
1317   using DerivedType = MessageValue2<RenderManager, Render::Geometry*, Render::VertexBuffer*>;
1318
1319   // Reserve some memory inside the render queue
1320   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1321
1322   // Construct message in the render queue memory; note that delete should not be called on the return value
1323   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::RemoveVertexBuffer, geometry, vertexBuffer);
1324 }
1325
1326 void UpdateManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
1327 {
1328   using DerivedType = MessageValue2<RenderManager, Render::Geometry*, Render::VertexBuffer*>;
1329
1330   // Reserve some memory inside the render queue
1331   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1332
1333   // Construct message in the render queue memory; note that delete should not be called on the return value
1334   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::AttachVertexBuffer, geometry, vertexBuffer);
1335 }
1336
1337 void UpdateManager::AddTexture(OwnerPointer<Render::Texture>& texture)
1338 {
1339   // Message has ownership of Texture while in transit from update -> render
1340   using DerivedType = MessageValue1<RenderManager, OwnerPointer<Render::Texture> >;
1341
1342   // Reserve some memory inside the render queue
1343   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1344
1345   // Construct message in the render queue memory; note that delete should not be called on the return value
1346   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::AddTexture, texture);
1347 }
1348
1349 void UpdateManager::RemoveTexture(Render::Texture* texture)
1350 {
1351   using DerivedType = MessageValue1<RenderManager, Render::Texture*>;
1352
1353   // Reserve some memory inside the render queue
1354   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1355
1356   // Construct message in the render queue memory; note that delete should not be called on the return value
1357   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::RemoveTexture, texture);
1358 }
1359
1360 void UpdateManager::UploadTexture(Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params)
1361 {
1362   using DerivedType = MessageValue3<RenderManager, Render::Texture*, PixelDataPtr, Texture::UploadParams>;
1363
1364   // Reserve some memory inside the message queue
1365   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1366
1367   // Construct message in the message queue memory; note that delete should not be called on the return value
1368   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::UploadTexture, texture, pixelData, params);
1369 }
1370
1371 void UpdateManager::GenerateMipmaps(Render::Texture* texture)
1372 {
1373   using DerivedType = MessageValue1<RenderManager, Render::Texture*>;
1374
1375   // Reserve some memory inside the render queue
1376   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1377
1378   // Construct message in the render queue memory; note that delete should not be called on the return value
1379   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::GenerateMipmaps, texture);
1380 }
1381
1382 void UpdateManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
1383 {
1384   using DerivedType = MessageValue1<RenderManager, OwnerPointer<Render::FrameBuffer> >;
1385
1386   // Reserve some memory inside the render queue
1387   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1388
1389   // Construct message in the render queue memory; note that delete should not be called on the return value
1390   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::AddFrameBuffer, frameBuffer);
1391 }
1392
1393 void UpdateManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
1394 {
1395   using DerivedType = MessageValue1<RenderManager, Render::FrameBuffer*>;
1396
1397   // Reserve some memory inside the render queue
1398   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1399
1400   // Construct message in the render queue memory; note that delete should not be called on the return value
1401   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::RemoveFrameBuffer, frameBuffer);
1402 }
1403
1404 void UpdateManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
1405 {
1406   using DerivedType = MessageValue4<RenderManager, Render::FrameBuffer*, Render::Texture*, uint32_t, uint32_t>;
1407
1408   // Reserve some memory inside the render queue
1409   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1410
1411   // Construct message in the render queue memory; note that delete should not be called on the return value
1412   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::AttachColorTextureToFrameBuffer, frameBuffer, texture, mipmapLevel, layer);
1413 }
1414
1415 void UpdateManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
1416 {
1417   using DerivedType = MessageValue3<RenderManager, Render::FrameBuffer*, Render::Texture*, uint32_t>;
1418
1419   // Reserve some memory inside the render queue
1420   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1421
1422   // Construct message in the render queue memory; note that delete should not be called on the return value
1423   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::AttachDepthTextureToFrameBuffer, frameBuffer, texture, mipmapLevel);
1424 }
1425
1426 void UpdateManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
1427 {
1428   using DerivedType = MessageValue3<RenderManager, Render::FrameBuffer*, Render::Texture*, uint32_t>;
1429
1430   // Reserve some memory inside the render queue
1431   uint32_t* slot = mImpl->renderQueue.ReserveMessageSlot(mSceneGraphBuffers.GetUpdateBufferIndex(), sizeof(DerivedType));
1432
1433   // Construct message in the render queue memory; note that delete should not be called on the return value
1434   new(slot) DerivedType(&mImpl->renderManager, &RenderManager::AttachDepthStencilTextureToFrameBuffer, frameBuffer, texture, mipmapLevel);
1435 }
1436
1437 } // namespace SceneGraph
1438
1439 } // namespace Internal
1440
1441 } // namespace Dali