Merge "Remove BaseHandle / BaseObject TypeTraits is trivialgit" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / animated-vector-image / animated-vector-image-visual.cpp
1 /*
2  * Copyright (c) 2024 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-toolkit/internal/visuals/animated-vector-image/animated-vector-image-visual.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/adaptor-framework/window-devel.h>
23 #include <dali/devel-api/common/stage.h>
24 #include <dali/devel-api/rendering/renderer-devel.h>
25 #include <dali/integration-api/adaptor-framework/adaptor.h>
26 #include <dali/integration-api/debug.h>
27 #include <dali/public-api/math/math-utils.h>
28 #include <dali/public-api/rendering/decorated-visual-renderer.h>
29
30 // INTERNAL INCLUDES
31 #include <dali-toolkit/devel-api/visuals/animated-vector-image-visual-signals-devel.h>
32 #include <dali-toolkit/devel-api/visuals/image-visual-properties-devel.h>
33 #include <dali-toolkit/devel-api/visuals/visual-actions-devel.h>
34 #include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-manager.h>
35 #include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
36 #include <dali-toolkit/internal/visuals/image-visual-shader-feature-builder.h>
37 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
38 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
39 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
40 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
41 #include <dali-toolkit/public-api/visuals/visual-properties.h>
42
43 namespace Dali
44 {
45 namespace Toolkit
46 {
47 namespace Internal
48 {
49 namespace
50 {
51 const int CUSTOM_PROPERTY_COUNT(1); // pixel area,
52
53 const Dali::Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
54
55 // stop behavior
56 DALI_ENUM_TO_STRING_TABLE_BEGIN(STOP_BEHAVIOR)
57   DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, CURRENT_FRAME)
58   DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, FIRST_FRAME)
59   DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, LAST_FRAME)
60 DALI_ENUM_TO_STRING_TABLE_END(STOP_BEHAVIOR)
61
62 // looping mode
63 DALI_ENUM_TO_STRING_TABLE_BEGIN(LOOPING_MODE)
64   DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::LoopingMode, RESTART)
65   DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::LoopingMode, AUTO_REVERSE)
66 DALI_ENUM_TO_STRING_TABLE_END(LOOPING_MODE)
67
68 #if defined(DEBUG_ENABLED)
69 Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VECTOR_ANIMATION");
70 #endif
71
72 } // unnamed namespace
73
74 AnimatedVectorImageVisualPtr AnimatedVectorImageVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties)
75 {
76   AnimatedVectorImageVisualPtr visual(new AnimatedVectorImageVisual(factoryCache, shaderFactory, imageUrl, ImageDimensions{}));
77   visual->SetProperties(properties);
78   visual->Initialize();
79   return visual;
80 }
81
82 AnimatedVectorImageVisualPtr AnimatedVectorImageVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, ImageDimensions size)
83 {
84   AnimatedVectorImageVisualPtr visual(new AnimatedVectorImageVisual(factoryCache, shaderFactory, imageUrl, size));
85   visual->Initialize();
86   return visual;
87 }
88
89 AnimatedVectorImageVisual::AnimatedVectorImageVisual(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, ImageDimensions size)
90 : Visual::Base(factoryCache, Visual::FittingMode::FILL, static_cast<Toolkit::Visual::Type>(Toolkit::DevelVisual::ANIMATED_VECTOR_IMAGE)),
91   mImageUrl(imageUrl),
92   mAnimationData(),
93   mVectorAnimationTask(new VectorAnimationTask(factoryCache)),
94   mImageVisualShaderFactory(shaderFactory),
95   mVisualSize(),
96   mVisualScale(Vector2::ONE),
97   mDesiredSize(size),
98   mPlacementActor(),
99   mPlayState(DevelImageVisual::PlayState::STOPPED),
100   mEventCallback(nullptr),
101   mLastSentPlayStateId(0u),
102   mLoadFailed(false),
103   mRendererAdded(false),
104   mCoreShutdown(false),
105   mRedrawInScalingDown(true),
106   mEnableFrameCache(false),
107   mUseNativeImage(false),
108   mNotifyAfterRasterization(false)
109 {
110   // the rasterized image is with pre-multiplied alpha format
111   mImpl->mFlags |= Visual::Base::Impl::IS_PREMULTIPLIED_ALPHA;
112
113   // By default, load a file synchronously
114   mImpl->mFlags |= Visual::Base::Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
115 }
116
117 AnimatedVectorImageVisual::~AnimatedVectorImageVisual()
118 {
119   if(!mCoreShutdown)
120   {
121     if(mImageUrl.IsBufferResource())
122     {
123       TextureManager& textureManager = mFactoryCache.GetTextureManager();
124       textureManager.RemoveEncodedImageBuffer(mImageUrl.GetUrl());
125     }
126
127     auto& vectorAnimationManager = mFactoryCache.GetVectorAnimationManager();
128     vectorAnimationManager.RemoveObserver(*this);
129
130     if(mEventCallback)
131     {
132       mFactoryCache.GetVectorAnimationManager().UnregisterEventCallback(mEventCallback);
133       mEventCallback = nullptr;
134     }
135
136     // Finalize animation task and disconnect the signal in the main thread
137     mVectorAnimationTask->ResourceReadySignal().Disconnect(this, &AnimatedVectorImageVisual::OnResourceReady);
138     mVectorAnimationTask->Finalize();
139   }
140 }
141
142 void AnimatedVectorImageVisual::VectorAnimationManagerDestroyed()
143 {
144   // Core is shutting down. Don't talk to the plugin any more.
145   mCoreShutdown = true;
146 }
147
148 void AnimatedVectorImageVisual::GetNaturalSize(Vector2& naturalSize)
149 {
150   if(mDesiredSize.GetWidth() > 0 && mDesiredSize.GetHeight() > 0)
151   {
152     naturalSize.x = mDesiredSize.GetWidth();
153     naturalSize.y = mDesiredSize.GetHeight();
154   }
155   else if(mVisualSize != Vector2::ZERO)
156   {
157     naturalSize = mVisualSize;
158   }
159   else
160   {
161     if(mLoadFailed && mImpl->mRenderer)
162     {
163       // Load failed, use broken image size
164       auto textureSet = mImpl->mRenderer.GetTextures();
165       if(textureSet && textureSet.GetTextureCount())
166       {
167         auto texture = textureSet.GetTexture(0);
168         if(texture)
169         {
170           naturalSize.x = texture.GetWidth();
171           naturalSize.y = texture.GetHeight();
172           return;
173         }
174       }
175     }
176     else
177     {
178       uint32_t width, height;
179       mVectorAnimationTask->GetDefaultSize(width, height);
180       naturalSize.x = width;
181       naturalSize.y = height;
182     }
183   }
184
185   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::GetNaturalSize: w = %f, h = %f [%p]\n", naturalSize.width, naturalSize.height, this);
186 }
187
188 void AnimatedVectorImageVisual::DoCreatePropertyMap(Property::Map& map) const
189 {
190   map.Clear();
191   map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::DevelVisual::ANIMATED_VECTOR_IMAGE);
192   if(mImageUrl.IsValid())
193   {
194     map.Insert(Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl());
195   }
196   map.Insert(Toolkit::DevelImageVisual::Property::LOOP_COUNT, mAnimationData.loopCount);
197
198   uint32_t startFrame, endFrame;
199   mVectorAnimationTask->GetPlayRange(startFrame, endFrame);
200
201   Property::Array playRange;
202   playRange.PushBack(static_cast<int32_t>(startFrame));
203   playRange.PushBack(static_cast<int32_t>(endFrame));
204   map.Insert(Toolkit::DevelImageVisual::Property::PLAY_RANGE, playRange);
205
206   map.Insert(Toolkit::DevelImageVisual::Property::PLAY_STATE, static_cast<int32_t>(mPlayState));
207   map.Insert(Toolkit::DevelImageVisual::Property::CURRENT_FRAME_NUMBER, static_cast<int32_t>(mVectorAnimationTask->GetCurrentFrameNumber()));
208   map.Insert(Toolkit::DevelImageVisual::Property::TOTAL_FRAME_NUMBER, static_cast<int32_t>(mVectorAnimationTask->GetTotalFrameNumber()));
209
210   map.Insert(Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, mAnimationData.stopBehavior);
211   map.Insert(Toolkit::DevelImageVisual::Property::LOOPING_MODE, mAnimationData.loopingMode);
212   map.Insert(Toolkit::DevelImageVisual::Property::REDRAW_IN_SCALING_DOWN, mRedrawInScalingDown);
213
214   Property::Map layerInfo;
215   mVectorAnimationTask->GetLayerInfo(layerInfo);
216   map.Insert(Toolkit::DevelImageVisual::Property::CONTENT_INFO, layerInfo);
217
218   Property::Map markerInfo;
219   mVectorAnimationTask->GetMarkerInfo(markerInfo);
220   map.Insert(Toolkit::DevelImageVisual::Property::MARKER_INFO, markerInfo);
221
222   map.Insert(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, IsSynchronousLoadingRequired());
223   map.Insert(Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth());
224   map.Insert(Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight());
225   map.Insert(Toolkit::DevelImageVisual::Property::ENABLE_FRAME_CACHE, mEnableFrameCache);
226   map.Insert(Toolkit::DevelImageVisual::Property::NOTIFY_AFTER_RASTERIZATION, mNotifyAfterRasterization);
227 }
228
229 void AnimatedVectorImageVisual::DoCreateInstancePropertyMap(Property::Map& map) const
230 {
231   // Do nothing
232 }
233
234 void AnimatedVectorImageVisual::EnablePreMultipliedAlpha(bool preMultiplied)
235 {
236   // Make always enable pre multiplied alpha whether preMultiplied value is false.
237   if(!preMultiplied)
238   {
239     DALI_LOG_WARNING("Note : AnimatedVectorVisual cannot disable PreMultipliedAlpha\n");
240   }
241 }
242
243 void AnimatedVectorImageVisual::DoSetProperties(const Property::Map& propertyMap)
244 {
245   // url already passed in from constructor
246   for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter)
247   {
248     KeyValuePair keyValue = propertyMap.GetKeyValue(iter);
249     if(keyValue.first.type == Property::Key::INDEX)
250     {
251       DoSetProperty(keyValue.first.indexKey, keyValue.second);
252     }
253     else
254     {
255       if(keyValue.first == LOOP_COUNT_NAME)
256       {
257         DoSetProperty(Toolkit::DevelImageVisual::Property::LOOP_COUNT, keyValue.second);
258       }
259       else if(keyValue.first == PLAY_RANGE_NAME)
260       {
261         DoSetProperty(Toolkit::DevelImageVisual::Property::PLAY_RANGE, keyValue.second);
262       }
263       else if(keyValue.first == STOP_BEHAVIOR_NAME)
264       {
265         DoSetProperty(Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, keyValue.second);
266       }
267       else if(keyValue.first == LOOPING_MODE_NAME)
268       {
269         DoSetProperty(Toolkit::DevelImageVisual::Property::LOOPING_MODE, keyValue.second);
270       }
271       else if(keyValue.first == REDRAW_IN_SCALING_DOWN_NAME)
272       {
273         DoSetProperty(Toolkit::DevelImageVisual::Property::REDRAW_IN_SCALING_DOWN, keyValue.second);
274       }
275       else if(keyValue.first == SYNCHRONOUS_LOADING)
276       {
277         DoSetProperty(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second);
278       }
279       else if(keyValue.first == IMAGE_DESIRED_WIDTH)
280       {
281         DoSetProperty(Toolkit::ImageVisual::Property::DESIRED_WIDTH, keyValue.second);
282       }
283       else if(keyValue.first == IMAGE_DESIRED_HEIGHT)
284       {
285         DoSetProperty(Toolkit::ImageVisual::Property::DESIRED_HEIGHT, keyValue.second);
286       }
287       else if(keyValue.first == ENABLE_FRAME_CACHE)
288       {
289         DoSetProperty(Toolkit::DevelImageVisual::Property::ENABLE_FRAME_CACHE, keyValue.second);
290       }
291       else if(keyValue.first == NOTIFY_AFTER_RASTERIZATION)
292       {
293         DoSetProperty(Toolkit::DevelImageVisual::Property::NOTIFY_AFTER_RASTERIZATION, keyValue.second);
294       }
295     }
296   }
297
298   TriggerVectorRasterization();
299 }
300
301 void AnimatedVectorImageVisual::DoSetProperty(Property::Index index, const Property::Value& value)
302 {
303   switch(index)
304   {
305     case Toolkit::DevelImageVisual::Property::LOOP_COUNT:
306     {
307       int32_t loopCount;
308       if(value.Get(loopCount))
309       {
310         mAnimationData.loopCount = loopCount;
311         mAnimationData.resendFlag |= VectorAnimationTask::RESEND_LOOP_COUNT;
312       }
313       break;
314     }
315     case Toolkit::DevelImageVisual::Property::PLAY_RANGE:
316     {
317       const Property::Array* array = value.GetArray();
318       if(array)
319       {
320         mAnimationData.playRange = *array;
321         mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_RANGE;
322       }
323       else if(value.GetType() == Property::STRING)
324       {
325         std::string markerName;
326         if(value.Get(markerName))
327         {
328           Property::Array array;
329           array.Add(markerName);
330           mAnimationData.playRange = std::move(array);
331           mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_RANGE;
332         }
333       }
334       break;
335     }
336     case Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR:
337     {
338       int32_t stopBehavior = mAnimationData.stopBehavior;
339       if(Scripting::GetEnumerationProperty(value, STOP_BEHAVIOR_TABLE, STOP_BEHAVIOR_TABLE_COUNT, stopBehavior))
340       {
341         mAnimationData.stopBehavior = DevelImageVisual::StopBehavior::Type(stopBehavior);
342         mAnimationData.resendFlag |= VectorAnimationTask::RESEND_STOP_BEHAVIOR;
343       }
344       break;
345     }
346     case Toolkit::DevelImageVisual::Property::LOOPING_MODE:
347     {
348       int32_t loopingMode = mAnimationData.loopingMode;
349       if(Scripting::GetEnumerationProperty(value, LOOPING_MODE_TABLE, LOOPING_MODE_TABLE_COUNT, loopingMode))
350       {
351         mAnimationData.loopingMode = DevelImageVisual::LoopingMode::Type(loopingMode);
352         mAnimationData.resendFlag |= VectorAnimationTask::RESEND_LOOPING_MODE;
353       }
354       break;
355     }
356     case Toolkit::DevelImageVisual::Property::REDRAW_IN_SCALING_DOWN:
357     {
358       bool redraw;
359       if(value.Get(redraw))
360       {
361         mRedrawInScalingDown = redraw;
362       }
363       break;
364     }
365     case Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING:
366     {
367       bool sync = false;
368       if(value.Get(sync))
369       {
370         if(sync)
371         {
372           mImpl->mFlags |= Visual::Base::Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
373         }
374         else
375         {
376           mImpl->mFlags &= ~Visual::Base::Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
377         }
378       }
379       break;
380     }
381     case Toolkit::ImageVisual::Property::DESIRED_WIDTH:
382     {
383       int32_t desiredWidth = 0;
384       if(value.Get(desiredWidth))
385       {
386         mDesiredSize.SetWidth(desiredWidth);
387       }
388       break;
389     }
390
391     case Toolkit::ImageVisual::Property::DESIRED_HEIGHT:
392     {
393       int32_t desiredHeight = 0;
394       if(value.Get(desiredHeight))
395       {
396         mDesiredSize.SetHeight(desiredHeight);
397       }
398       break;
399     }
400
401     case Toolkit::DevelImageVisual::Property::ENABLE_FRAME_CACHE:
402     {
403       bool enableFrameCache = false;
404       if(value.Get(enableFrameCache))
405       {
406         mEnableFrameCache = enableFrameCache;
407         if(mVectorAnimationTask)
408         {
409           mVectorAnimationTask->KeepRasterizedBuffer(mEnableFrameCache);
410         }
411       }
412       break;
413     }
414
415     case Toolkit::DevelImageVisual::Property::NOTIFY_AFTER_RASTERIZATION:
416     {
417       bool notifyAfterRasterization = false;
418       if(value.Get(notifyAfterRasterization))
419       {
420         if(mNotifyAfterRasterization != notifyAfterRasterization)
421         {
422           mNotifyAfterRasterization = notifyAfterRasterization;
423
424           mAnimationData.notifyAfterRasterization = mNotifyAfterRasterization;
425           mAnimationData.resendFlag |= VectorAnimationTask::RESEND_NOTIFY_AFTER_RASTERIZATION;
426         }
427       }
428       break;
429     }
430   }
431 }
432
433 void AnimatedVectorImageVisual::OnInitialize(void)
434 {
435   mVectorAnimationTask->ResourceReadySignal().Connect(this, &AnimatedVectorImageVisual::OnResourceReady);
436   mVectorAnimationTask->SetAnimationFinishedCallback(MakeCallback(this, &AnimatedVectorImageVisual::OnAnimationFinished));
437
438   EncodedImageBuffer encodedImageBuffer;
439
440   if(mImageUrl.IsBufferResource())
441   {
442     // Increase reference count of External Resources :
443     // EncodedImageBuffer.
444     // Reference count will be decreased at destructor of the visual.
445     TextureManager& textureManager = mFactoryCache.GetTextureManager();
446     textureManager.UseExternalResource(mImageUrl.GetUrl());
447
448     encodedImageBuffer = textureManager.GetEncodedImageBuffer(mImageUrl.GetUrl());
449   }
450
451   mVectorAnimationTask->KeepRasterizedBuffer(mEnableFrameCache);
452   mVectorAnimationTask->RequestLoad(mImageUrl, encodedImageBuffer, IsSynchronousLoadingRequired());
453
454   auto& vectorAnimationManager = mFactoryCache.GetVectorAnimationManager();
455   vectorAnimationManager.AddObserver(*this);
456
457   Shader shader = GenerateShader();
458
459   Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
460
461   mImpl->mRenderer = DecoratedVisualRenderer::New(geometry, shader);
462   mImpl->mRenderer.ReserveCustomProperties(CUSTOM_PROPERTY_COUNT);
463
464   TextureSet textureSet = TextureSet::New();
465   mImpl->mRenderer.SetTextures(textureSet);
466
467   // Register transform properties
468   mImpl->mTransform.SetUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
469
470   mVectorAnimationTask->SetRenderer(mImpl->mRenderer);
471 }
472
473 void AnimatedVectorImageVisual::DoSetOnScene(Actor& actor)
474 {
475   // Defer the rasterisation task until we get given a size (by Size Negotiation algorithm)
476
477   // Hold the weak handle of the placement actor and delay the adding of renderer until the rasterization is finished.
478   mPlacementActor = actor;
479
480   if(mLoadFailed)
481   {
482     Vector2 imageSize = actor.GetProperty(Actor::Property::SIZE).Get<Vector2>();
483     mFactoryCache.UpdateBrokenImageRenderer(mImpl->mRenderer, imageSize, false);
484     actor.AddRenderer(mImpl->mRenderer);
485     mRendererAdded = true;
486     ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
487   }
488   else
489   {
490     // Add property notification for scaling & size
491     mScaleNotification = actor.AddPropertyNotification(Actor::Property::WORLD_SCALE, StepCondition(0.1f, 1.0f));
492     mScaleNotification.NotifySignal().Connect(this, &AnimatedVectorImageVisual::OnScaleNotification);
493
494     mSizeNotification = actor.AddPropertyNotification(Actor::Property::SIZE, StepCondition(3.0f));
495     mSizeNotification.NotifySignal().Connect(this, &AnimatedVectorImageVisual::OnSizeNotification);
496
497     DevelActor::VisibilityChangedSignal(actor).Connect(this, &AnimatedVectorImageVisual::OnControlVisibilityChanged);
498
499     Window window = DevelWindow::Get(actor);
500     if(window)
501     {
502       DevelWindow::VisibilityChangedSignal(window).Connect(this, &AnimatedVectorImageVisual::OnWindowVisibilityChanged);
503     }
504
505     if(mImpl->mEventObserver)
506     {
507       // The visual needs it's size set before it can be rasterized hence request relayout once on stage
508       mImpl->mEventObserver->RelayoutRequest(*this);
509     }
510
511     mAnimationData.resendFlag |= VectorAnimationTask::RESEND_NEED_RESOURCE_READY;
512     TriggerVectorRasterization();
513   }
514
515   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::DoSetOnScene [%p]\n", this);
516 }
517
518 void AnimatedVectorImageVisual::DoSetOffScene(Actor& actor)
519 {
520   StopAnimation();
521   TriggerVectorRasterization();
522
523   if(mImpl->mRenderer)
524   {
525     actor.RemoveRenderer(mImpl->mRenderer);
526     mRendererAdded = false;
527   }
528
529   // Remove property notification
530   actor.RemovePropertyNotification(mScaleNotification);
531   actor.RemovePropertyNotification(mSizeNotification);
532
533   DevelActor::VisibilityChangedSignal(actor).Disconnect(this, &AnimatedVectorImageVisual::OnControlVisibilityChanged);
534
535   Window window = DevelWindow::Get(actor);
536   if(window)
537   {
538     DevelWindow::VisibilityChangedSignal(window).Disconnect(this, &AnimatedVectorImageVisual::OnWindowVisibilityChanged);
539   }
540
541   mPlacementActor.Reset();
542
543   // Reset the visual size to zero so that when adding the actor back to stage the rasterization is forced
544   mVisualSize           = Vector2::ZERO;
545   mVisualScale          = Vector2::ONE;
546   mAnimationData.width  = 0;
547   mAnimationData.height = 0;
548
549   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::DoSetOffScene [%p]\n", this);
550 }
551
552 void AnimatedVectorImageVisual::OnSetTransform()
553 {
554   Vector2 visualSize = mImpl->mTransform.GetVisualSize(mImpl->mControlSize);
555
556   if(IsOnScene() && visualSize != mVisualSize)
557   {
558     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnSetTransform: width = %f, height = %f [%p]\n", visualSize.width, visualSize.height, this);
559
560     mVisualSize = visualSize;
561
562     SetVectorImageSize();
563
564     if(mPlayState == DevelImageVisual::PlayState::PLAYING && mAnimationData.playState != DevelImageVisual::PlayState::PLAYING)
565     {
566       mAnimationData.playState = DevelImageVisual::PlayState::PLAYING;
567       mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE;
568     }
569
570     TriggerVectorRasterization();
571   }
572 }
573
574 void AnimatedVectorImageVisual::UpdateShader()
575 {
576   if(mImpl->mRenderer)
577   {
578     Shader shader = GenerateShader();
579     mImpl->mRenderer.SetShader(shader);
580   }
581 }
582
583 void AnimatedVectorImageVisual::OnDoAction(const Property::Index actionId, const Property::Value& attributes)
584 {
585   // Check if action is valid for this visual type and perform action if possible
586   switch(actionId)
587   {
588     case DevelAnimatedVectorImageVisual::Action::PLAY:
589     {
590       if(IsOnScene() && mVisualSize != Vector2::ZERO)
591       {
592         // Always resend Playing state. If task is already playing, it will be ignored at Rasterize time.
593         mAnimationData.playState = DevelImageVisual::PlayState::PLAYING;
594         mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE;
595       }
596       mPlayState = DevelImageVisual::PlayState::PLAYING;
597       break;
598     }
599     case DevelAnimatedVectorImageVisual::Action::PAUSE:
600     {
601       if(mAnimationData.playState == DevelImageVisual::PlayState::PLAYING)
602       {
603         mAnimationData.playState = DevelImageVisual::PlayState::PAUSED;
604         mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE;
605       }
606       mPlayState = DevelImageVisual::PlayState::PAUSED;
607       break;
608     }
609     case DevelAnimatedVectorImageVisual::Action::STOP:
610     {
611       if(mAnimationData.playState != DevelImageVisual::PlayState::STOPPED)
612       {
613         mAnimationData.playState = DevelImageVisual::PlayState::STOPPED;
614         mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE;
615       }
616       mPlayState = DevelImageVisual::PlayState::STOPPED;
617       break;
618     }
619     case DevelAnimatedVectorImageVisual::Action::JUMP_TO:
620     {
621       int32_t frameNumber;
622       if(attributes.Get(frameNumber))
623       {
624         mAnimationData.currentFrame = frameNumber;
625         mAnimationData.resendFlag |= VectorAnimationTask::RESEND_CURRENT_FRAME;
626       }
627       break;
628     }
629     case DevelAnimatedVectorImageVisual::Action::FLUSH:
630     {
631       if(DALI_LIKELY(!mCoreShutdown))
632       {
633         SendAnimationData();
634       }
635       break;
636     }
637   }
638
639   TriggerVectorRasterization();
640 }
641
642 void AnimatedVectorImageVisual::OnDoActionExtension(const Property::Index actionId, Dali::Any attributes)
643 {
644   switch(actionId)
645   {
646     case DevelAnimatedVectorImageVisual::Action::SET_DYNAMIC_PROPERTY:
647     {
648       DevelAnimatedVectorImageVisual::DynamicPropertyInfo info = AnyCast<DevelAnimatedVectorImageVisual::DynamicPropertyInfo>(attributes);
649       mAnimationData.dynamicProperties.push_back(info);
650       mAnimationData.resendFlag |= VectorAnimationTask::RESEND_DYNAMIC_PROPERTY;
651       break;
652     }
653   }
654
655   TriggerVectorRasterization();
656 }
657
658 void AnimatedVectorImageVisual::OnResourceReady(VectorAnimationTask::ResourceStatus status)
659 {
660   AnimatedVectorImageVisualPtr self = this; // Keep reference until this API finished
661
662   if(status == VectorAnimationTask::ResourceStatus::LOADED)
663   {
664     if(mImpl->mEventObserver)
665     {
666       mImpl->mEventObserver->RelayoutRequest(*this);
667     }
668   }
669   else
670   {
671     mLoadFailed = status == VectorAnimationTask::ResourceStatus::FAILED ? true : false;
672     if(status == VectorAnimationTask::ResourceStatus::READY)
673     {
674       // Texture was ready. Change the shader if we need.
675       bool useNativeImage = false;
676       if(mImpl->mRenderer)
677       {
678         auto textureSet = mImpl->mRenderer.GetTextures();
679         if(textureSet && textureSet.GetTextureCount() > 0)
680         {
681           auto texture = textureSet.GetTexture(0u);
682           if(texture)
683           {
684             useNativeImage = DevelTexture::IsNative(texture);
685
686             if(mUseNativeImage != useNativeImage)
687             {
688               mUseNativeImage = useNativeImage;
689               UpdateShader();
690             }
691           }
692         }
693       }
694     }
695
696     // If weak handle is holding a placement actor, it is the time to add the renderer to actor.
697     Actor actor = mPlacementActor.GetHandle();
698     if(actor && !mRendererAdded)
699     {
700       if(!mLoadFailed)
701       {
702         actor.AddRenderer(mImpl->mRenderer);
703         ResourceReady(Toolkit::Visual::ResourceStatus::READY);
704       }
705       else
706       {
707         Vector2 imageSize = actor.GetProperty(Actor::Property::SIZE).Get<Vector2>();
708         mFactoryCache.UpdateBrokenImageRenderer(mImpl->mRenderer, imageSize, false);
709         actor.AddRenderer(mImpl->mRenderer);
710         ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
711       }
712
713       mRendererAdded = true;
714     }
715   }
716
717   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "status = %d [%p]\n", status, this);
718 }
719
720 void AnimatedVectorImageVisual::OnAnimationFinished(uint32_t playStateId)
721 {
722   // Only send event when animation is finished by the last Play/Pause/Stop request.
723   if(mLastSentPlayStateId != playStateId)
724   {
725     return;
726   }
727
728   AnimatedVectorImageVisualPtr self = this; // Keep reference until this API finished
729
730   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnAnimationFinished: action state = %d [%p]\n", mPlayState, this);
731
732   if(mPlayState != DevelImageVisual::PlayState::STOPPED)
733   {
734     mPlayState = DevelImageVisual::PlayState::STOPPED;
735
736     mAnimationData.playState = DevelImageVisual::PlayState::STOPPED;
737
738     if(mImpl->mEventObserver)
739     {
740       mImpl->mEventObserver->NotifyVisualEvent(*this, DevelAnimatedVectorImageVisual::Signal::ANIMATION_FINISHED);
741     }
742   }
743
744   if(!mNotifyAfterRasterization && mImpl->mRenderer)
745   {
746     mImpl->mRenderer.SetProperty(DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::IF_REQUIRED);
747   }
748 }
749
750 void AnimatedVectorImageVisual::SendAnimationData()
751 {
752   if(mAnimationData.resendFlag)
753   {
754     if(mAnimationData.resendFlag & VectorAnimationTask::RESEND_PLAY_STATE)
755     {
756       // Keep last sent playId. It will be used when we try to emit AnimationFinished signal.
757       // The OnAnimationFinished signal what before Play/Pause/Stop action send could be come after action sent.
758       // To ensure the OnAnimationFinished signal comes belong to what we sent, we need to keep last sent playId.
759       mAnimationData.playStateId = ++mLastSentPlayStateId;
760     }
761     mVectorAnimationTask->SetAnimationData(mAnimationData);
762
763     if(mImpl->mRenderer &&
764        ((mAnimationData.resendFlag & VectorAnimationTask::RESEND_PLAY_STATE) ||
765         (mAnimationData.resendFlag & VectorAnimationTask::RESEND_NOTIFY_AFTER_RASTERIZATION)))
766     {
767       if(!mNotifyAfterRasterization && mPlayState == DevelImageVisual::PlayState::PLAYING)
768       {
769         // Make rendering behaviour if we don't notify after rasterization, but animation playing.
770         mImpl->mRenderer.SetProperty(DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::CONTINUOUSLY);
771       }
772       else
773       {
774         // Otherwise, notify will be sended after rasterization. Make behaviour as required.
775         mImpl->mRenderer.SetProperty(DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::IF_REQUIRED);
776       }
777     }
778
779     mAnimationData.resendFlag = 0;
780   }
781 }
782
783 void AnimatedVectorImageVisual::SetVectorImageSize()
784 {
785   uint32_t width, height;
786   if(mDesiredSize.GetWidth() > 0 && mDesiredSize.GetHeight() > 0)
787   {
788     width  = mDesiredSize.GetWidth();
789     height = mDesiredSize.GetHeight();
790   }
791   else
792   {
793     width  = static_cast<uint32_t>(mVisualSize.width * mVisualScale.width);
794     height = static_cast<uint32_t>(mVisualSize.height * mVisualScale.height);
795   }
796
797   if(mAnimationData.width != width || mAnimationData.height != height)
798   {
799     mAnimationData.width  = width;
800     mAnimationData.height = height;
801     mAnimationData.resendFlag |= VectorAnimationTask::RESEND_SIZE;
802   }
803 }
804
805 void AnimatedVectorImageVisual::StopAnimation()
806 {
807   if(mAnimationData.playState != DevelImageVisual::PlayState::STOPPED)
808   {
809     mAnimationData.playState = DevelImageVisual::PlayState::STOPPED;
810     mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE;
811
812     mPlayState = DevelImageVisual::PlayState::STOPPED;
813   }
814 }
815
816 void AnimatedVectorImageVisual::TriggerVectorRasterization()
817 {
818   if(!mEventCallback && !mCoreShutdown)
819   {
820     mEventCallback               = MakeCallback(this, &AnimatedVectorImageVisual::OnProcessEvents);
821     auto& vectorAnimationManager = mFactoryCache.GetVectorAnimationManager();
822     vectorAnimationManager.RegisterEventCallback(mEventCallback);
823     Stage::GetCurrent().KeepRendering(0.0f); // Trigger event processing
824   }
825 }
826
827 void AnimatedVectorImageVisual::OnScaleNotification(PropertyNotification& source)
828 {
829   Actor actor = mPlacementActor.GetHandle();
830   if(actor)
831   {
832     Vector3 scale = actor.GetProperty<Vector3>(Actor::Property::WORLD_SCALE);
833
834     if((!Dali::Equals(mVisualScale.width, scale.width) || !Dali::Equals(mVisualScale.height, scale.height)) && (mRedrawInScalingDown || scale.width >= 1.0f || scale.height >= 1.0f))
835     {
836       mVisualScale.width  = scale.width;
837       mVisualScale.height = scale.height;
838
839       DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnScaleNotification: scale = %f, %f [%p]\n", mVisualScale.width, mVisualScale.height, this);
840
841       SetVectorImageSize();
842       SendAnimationData();
843
844       Stage::GetCurrent().KeepRendering(0.0f); // Trigger event processing
845     }
846   }
847 }
848
849 void AnimatedVectorImageVisual::OnSizeNotification(PropertyNotification& source)
850 {
851   Actor actor = mPlacementActor.GetHandle();
852   if(actor)
853   {
854     Vector3 size = actor.GetCurrentProperty<Vector3>(Actor::Property::SIZE);
855
856     if(!Dali::Equals(mVisualSize.width, size.width) || !Dali::Equals(mVisualSize.height, size.height))
857     {
858       mVisualSize.width  = size.width;
859       mVisualSize.height = size.height;
860
861       DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnSizeNotification: size = %f, %f [%p]\n", mVisualSize.width, mVisualSize.height, this);
862
863       SetVectorImageSize();
864       SendAnimationData();
865
866       Stage::GetCurrent().KeepRendering(0.0f); // Trigger event processing
867     }
868   }
869 }
870
871 void AnimatedVectorImageVisual::OnControlVisibilityChanged(Actor actor, bool visible, DevelActor::VisibilityChange::Type type)
872 {
873   if(!visible)
874   {
875     StopAnimation();
876     TriggerVectorRasterization();
877
878     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnControlVisibilityChanged: invisibile. Pause animation [%p]\n", this);
879   }
880 }
881
882 void AnimatedVectorImageVisual::OnWindowVisibilityChanged(Window window, bool visible)
883 {
884   if(!visible)
885   {
886     StopAnimation();
887     TriggerVectorRasterization();
888
889     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnWindowVisibilityChanged: invisibile. Pause animation [%p]\n", this);
890   }
891 }
892
893 void AnimatedVectorImageVisual::OnProcessEvents()
894 {
895   SendAnimationData();
896
897   mEventCallback = nullptr; // The callback will be deleted in the VectorAnimationManager
898 }
899
900 Shader AnimatedVectorImageVisual::GenerateShader() const
901 {
902   Shader shader;
903   if(mImpl->mCustomShader)
904   {
905     shader = Shader::New(mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource().data() : mImpl->mCustomShader->mVertexShader,
906                          mImpl->mCustomShader->mFragmentShader.empty() ? mImageVisualShaderFactory.GetFragmentShaderSource().data() : mImpl->mCustomShader->mFragmentShader,
907                          mImpl->mCustomShader->mHints);
908
909     shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
910   }
911   else
912   {
913     shader = mImageVisualShaderFactory.GetShader(
914       mFactoryCache,
915       ImageVisualShaderFeatureBuilder()
916         .EnableRoundedCorner(IsRoundedCornerRequired())
917         .EnableBorderline(IsBorderlineRequired())
918         .SetTextureForFragmentShaderCheck(mUseNativeImage ? mImpl->mRenderer.GetTextures().GetTexture(0) : Dali::Texture()));
919   }
920   return shader;
921 }
922
923 } // namespace Internal
924
925 } // namespace Toolkit
926
927 } // namespace Dali