(Vector) Use scaling factor for rasterization
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / animated-vector-image / animated-vector-image-visual.cpp
1 /*
2  * Copyright (c) 2019 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali-toolkit/internal/visuals/animated-vector-image/animated-vector-image-visual.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/public-api/common/stage.h>
23 #include <dali/devel-api/rendering/renderer-devel.h>
24 #include <dali/integration-api/debug.h>
25
26 // INTERNAL INCLUDES
27 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
28 #include <dali-toolkit/public-api/visuals/visual-properties.h>
29 #include <dali-toolkit/devel-api/visuals/image-visual-properties-devel.h>
30 #include <dali-toolkit/devel-api/visuals/animated-vector-image-visual-signals-devel.h>
31 #include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
32 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
33 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
34 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
35
36 namespace Dali
37 {
38
39 namespace Toolkit
40 {
41
42 namespace Internal
43 {
44
45 namespace
46 {
47
48 constexpr auto LOOP_FOREVER = -1;
49
50 const Dali::Vector4 FULL_TEXTURE_RECT( 0.f, 0.f, 1.f, 1.f );
51
52 // Flags for re-sending data to the rasterize thread
53 enum Flags
54 {
55   RESEND_PLAY_RANGE    = 1 << 0,
56   RESEND_LOOP_COUNT    = 1 << 1,
57   RESEND_STOP_BEHAVIOR = 1 << 2,
58   RESEND_LOOPING_MODE  = 1 << 3
59 };
60
61 // stop behavior
62 DALI_ENUM_TO_STRING_TABLE_BEGIN( STOP_BEHAVIOR )
63 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::StopBehavior, CURRENT_FRAME )
64 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::StopBehavior, FIRST_FRAME )
65 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::StopBehavior, LAST_FRAME )
66 DALI_ENUM_TO_STRING_TABLE_END( STOP_BEHAVIOR )
67
68 // looping mode
69 DALI_ENUM_TO_STRING_TABLE_BEGIN( LOOPING_MODE )
70 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::LoopingMode, RESTART )
71 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::LoopingMode, AUTO_REVERSE )
72 DALI_ENUM_TO_STRING_TABLE_END( LOOPING_MODE )
73
74 #if defined(DEBUG_ENABLED)
75 Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_VECTOR_ANIMATION" );
76 #endif
77
78 } // unnamed namespace
79
80 AnimatedVectorImageVisualPtr AnimatedVectorImageVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties )
81 {
82   AnimatedVectorImageVisualPtr visual( new AnimatedVectorImageVisual( factoryCache, shaderFactory, imageUrl ) );
83   visual->SetProperties( properties );
84
85   return visual;
86 }
87
88 AnimatedVectorImageVisualPtr AnimatedVectorImageVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl )
89 {
90   AnimatedVectorImageVisualPtr visual( new AnimatedVectorImageVisual( factoryCache, shaderFactory, imageUrl ) );
91
92   return visual;
93 }
94
95 AnimatedVectorImageVisual::AnimatedVectorImageVisual( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl )
96 : Visual::Base( factoryCache, Visual::FittingMode::FILL ),
97   mImageVisualShaderFactory( shaderFactory ),
98   mUrl( imageUrl ),
99   mVectorRasterizeThread( imageUrl.GetUrl() ),
100   mVisualSize(),
101   mVisualScale( Vector2::ONE ),
102   mPlacementActor(),
103   mLoopCount( LOOP_FOREVER ),
104   mStartFrame( 0 ),
105   mEndFrame( 0 ),
106   mResendFlag( 0 ),
107   mActionStatus( DevelAnimatedVectorImageVisual::Action::STOP ),
108   mStopBehavior( DevelImageVisual::StopBehavior::CURRENT_FRAME ),
109   mLoopingMode( DevelImageVisual::LoopingMode::RESTART ),
110   mRendererAdded( false )
111 {
112   // the rasterized image is with pre-multiplied alpha format
113   mImpl->mFlags |= Impl::IS_PREMULTIPLIED_ALPHA;
114
115   mVectorRasterizeThread.UploadCompletedSignal().Connect( this, &AnimatedVectorImageVisual::OnUploadCompleted );
116   mVectorRasterizeThread.SetAnimationFinishedCallback( new EventThreadCallback( MakeCallback( this, &AnimatedVectorImageVisual::OnAnimationFinished ) ) );
117
118   mVectorRasterizeThread.Start();
119 }
120
121 AnimatedVectorImageVisual::~AnimatedVectorImageVisual()
122 {
123 }
124
125 void AnimatedVectorImageVisual::GetNaturalSize( Vector2& naturalSize )
126 {
127   if( mVisualSize != Vector2::ZERO )
128   {
129     naturalSize = mVisualSize;
130   }
131   else
132   {
133     uint32_t width, height;
134     mVectorRasterizeThread.GetDefaultSize( width, height );
135     naturalSize.x = width;
136     naturalSize.y = height;
137   }
138
139   DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::GetNaturalSize: w = %f, h = %f [%p]\n", naturalSize.width, naturalSize.height, this );
140 }
141
142 void AnimatedVectorImageVisual::DoCreatePropertyMap( Property::Map& map ) const
143 {
144   map.Clear();
145   map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::DevelVisual::ANIMATED_VECTOR_IMAGE );
146   if( mUrl.IsValid() )
147   {
148     map.Insert( Toolkit::ImageVisual::Property::URL, mUrl.GetUrl() );
149   }
150   map.Insert( Toolkit::DevelImageVisual::Property::LOOP_COUNT, mLoopCount );
151
152   Property::Array playRange;
153   playRange.PushBack( mStartFrame );
154   playRange.PushBack( mEndFrame );
155   map.Insert( Toolkit::DevelImageVisual::Property::PLAY_RANGE, playRange );
156
157   map.Insert( Toolkit::DevelImageVisual::Property::PLAY_STATE, static_cast< int >( mVectorRasterizeThread.GetPlayState() ) );
158   map.Insert( Toolkit::DevelImageVisual::Property::CURRENT_FRAME_NUMBER, static_cast< int32_t >( mVectorRasterizeThread.GetCurrentFrameNumber() ) );
159   map.Insert( Toolkit::DevelImageVisual::Property::TOTAL_FRAME_NUMBER, static_cast< int32_t >( mVectorRasterizeThread.GetTotalFrameNumber() ) );
160
161   map.Insert( Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, mStopBehavior );
162   map.Insert( Toolkit::DevelImageVisual::Property::LOOPING_MODE, mLoopingMode );
163 }
164
165 void AnimatedVectorImageVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
166 {
167   // Do nothing
168 }
169
170 void AnimatedVectorImageVisual::DoSetProperties( const Property::Map& propertyMap )
171 {
172   // url already passed in from constructor
173   for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter )
174   {
175     KeyValuePair keyValue = propertyMap.GetKeyValue( iter );
176     if( keyValue.first.type == Property::Key::INDEX )
177     {
178       DoSetProperty( keyValue.first.indexKey, keyValue.second );
179     }
180     else
181     {
182        if( keyValue.first == LOOP_COUNT_NAME )
183        {
184           DoSetProperty( Toolkit::DevelImageVisual::Property::LOOP_COUNT, keyValue.second );
185        }
186        else if( keyValue.first == PLAY_RANGE_NAME )
187        {
188           DoSetProperty( Toolkit::DevelImageVisual::Property::PLAY_RANGE, keyValue.second );
189        }
190        else if( keyValue.first == STOP_BEHAVIOR_NAME )
191        {
192           DoSetProperty( Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, keyValue.second );
193        }
194        else if( keyValue.first == LOOPING_MODE_NAME )
195        {
196           DoSetProperty( Toolkit::DevelImageVisual::Property::LOOPING_MODE, keyValue.second );
197        }
198     }
199   }
200 }
201
202 void AnimatedVectorImageVisual::DoSetProperty( Property::Index index, const Property::Value& value )
203 {
204   switch(index)
205   {
206     case Toolkit::DevelImageVisual::Property::LOOP_COUNT:
207     {
208       int32_t loopCount;
209       if( value.Get( loopCount ) )
210       {
211         mLoopCount = loopCount;
212         mResendFlag |= RESEND_LOOP_COUNT;
213       }
214       break;
215     }
216     case Toolkit::DevelImageVisual::Property::PLAY_RANGE:
217     {
218       Property::Array* array = value.GetArray();
219       if( array )
220       {
221         size_t count = array->Count();
222         if( count >= 2 )
223         {
224           int startFrame, endFrame;
225           int totalFrame = mVectorRasterizeThread.GetTotalFrameNumber();
226           array->GetElementAt( 0 ).Get( startFrame );
227           array->GetElementAt( 1 ).Get( endFrame );
228
229           if( startFrame >= 0 && startFrame < totalFrame && endFrame >= 0 && endFrame < totalFrame )
230           {
231             mStartFrame = startFrame;
232             mEndFrame = endFrame;
233             mResendFlag |= RESEND_PLAY_RANGE;
234           }
235           else
236           {
237             DALI_LOG_ERROR( "Invalid play range [%d, %d / %d]\n", startFrame, endFrame, totalFrame );
238           }
239         }
240       }
241       break;
242     }
243     case Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR:
244     {
245       int32_t stopBehavior;
246       Scripting::GetEnumerationProperty( value, STOP_BEHAVIOR_TABLE, STOP_BEHAVIOR_TABLE_COUNT, stopBehavior );
247       mStopBehavior = DevelImageVisual::StopBehavior::Type( stopBehavior );
248       mResendFlag |= RESEND_STOP_BEHAVIOR;
249       break;
250     }
251     case Toolkit::DevelImageVisual::Property::LOOPING_MODE:
252     {
253       int32_t loopingMode;
254       Scripting::GetEnumerationProperty( value, LOOPING_MODE_TABLE, LOOPING_MODE_TABLE_COUNT, loopingMode );
255       mLoopingMode = DevelImageVisual::LoopingMode::Type( loopingMode );
256       mResendFlag |= RESEND_LOOPING_MODE;
257       break;
258     }
259   }
260 }
261
262 void AnimatedVectorImageVisual::DoSetOnStage( Actor& actor )
263 {
264   Shader shader;
265
266   if( mImpl->mCustomShader )
267   {
268     shader = Shader::New( mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource() : mImpl->mCustomShader->mVertexShader,
269                           mImpl->mCustomShader->mFragmentShader.empty() ? mImageVisualShaderFactory.GetFragmentShaderSource() : mImpl->mCustomShader->mFragmentShader,
270                           mImpl->mCustomShader->mHints );
271
272     shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
273   }
274   else
275   {
276     shader = mImageVisualShaderFactory.GetShader( mFactoryCache, false, true );
277   }
278
279   Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
280
281   mImpl->mRenderer = Renderer::New( geometry, shader );
282
283   TextureSet textureSet = TextureSet::New();
284   mImpl->mRenderer.SetTextures( textureSet );
285
286   // Register transform properties
287   mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
288
289   // Defer the rasterisation task until we get given a size (by Size Negotiation algorithm)
290
291   // Hold the weak handle of the placement actor and delay the adding of renderer until the rasterization is finished.
292   mPlacementActor = actor;
293
294   mVectorRasterizeThread.SetRenderer( mImpl->mRenderer );
295
296   // Add property notification for scaling & size
297   mScaleNotification = actor.AddPropertyNotification( Actor::Property::WORLD_SCALE, StepCondition( 0.1f, 1.0f ) );
298   mScaleNotification.NotifySignal().Connect( this, &AnimatedVectorImageVisual::OnScaleNotification );
299
300   mSizeNotification = actor.AddPropertyNotification( Actor::Property::SIZE, StepCondition( 3.0f ) );
301   mSizeNotification.NotifySignal().Connect( this, &AnimatedVectorImageVisual::OnSizeNotification );
302
303   DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::DoSetOnStage [%p]\n", this );
304 }
305
306 void AnimatedVectorImageVisual::DoSetOffStage( Actor& actor )
307 {
308   mVectorRasterizeThread.PauseAnimation();
309
310   mActionStatus = DevelAnimatedVectorImageVisual::Action::PAUSE;
311
312   if( mImpl->mRenderer )
313   {
314     mImpl->mRenderer.SetProperty( DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::IF_REQUIRED );
315
316     actor.RemoveRenderer( mImpl->mRenderer );
317     mImpl->mRenderer.Reset();
318
319     mRendererAdded = false;
320   }
321
322   // Remove property notification
323   actor.RemovePropertyNotification( mScaleNotification );
324   actor.RemovePropertyNotification( mSizeNotification );
325
326   mPlacementActor.Reset();
327
328   // Reset the visual size to zero so that when adding the actor back to stage the rasterization is forced
329   mVisualSize = Vector2::ZERO;
330   mVisualScale = Vector2::ONE;
331
332   DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::DoSetOffStage [%p]\n", this );
333 }
334
335 void AnimatedVectorImageVisual::OnSetTransform()
336 {
337   Vector2 visualSize = mImpl->mTransform.GetVisualSize( mImpl->mControlSize );
338
339   if( IsOnStage() && visualSize != mVisualSize )
340   {
341     DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnSetTransform: width = %f, height = %f [%p]\n", visualSize.width, visualSize.height, this );
342
343     mVisualSize = visualSize;
344
345     SetVectorImageSize();
346
347     SendAnimationData();
348
349     if( mActionStatus == DevelAnimatedVectorImageVisual::Action::PLAY )
350     {
351       mVectorRasterizeThread.PlayAnimation();
352
353       mImpl->mRenderer.SetProperty( DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::CONTINUOUSLY );
354     }
355     else
356     {
357       // Render one frame
358       mVectorRasterizeThread.RenderFrame();
359     }
360   }
361 }
362
363 void AnimatedVectorImageVisual::OnDoAction( const Property::Index actionId, const Property::Value& attributes )
364 {
365   // Check if action is valid for this visual type and perform action if possible
366   switch( actionId )
367   {
368     case DevelAnimatedVectorImageVisual::Action::PLAY:
369     {
370       if( IsOnStage() && mVisualSize != Vector2::ZERO )
371       {
372         mVectorRasterizeThread.PlayAnimation();
373
374         mImpl->mRenderer.SetProperty( DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::CONTINUOUSLY );
375       }
376       mActionStatus = DevelAnimatedVectorImageVisual::Action::PLAY;
377       break;
378     }
379     case DevelAnimatedVectorImageVisual::Action::PAUSE:
380     {
381       mVectorRasterizeThread.PauseAnimation();
382
383       if( mImpl->mRenderer )
384       {
385         mImpl->mRenderer.SetProperty( DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::IF_REQUIRED );
386       }
387
388       mActionStatus = DevelAnimatedVectorImageVisual::Action::PAUSE;
389       break;
390     }
391     case DevelAnimatedVectorImageVisual::Action::STOP:
392     {
393       if( mVectorRasterizeThread.GetPlayState() != DevelImageVisual::PlayState::STOPPED )
394       {
395         mVectorRasterizeThread.StopAnimation();
396
397         OnAnimationFinished();
398       }
399       mActionStatus = DevelAnimatedVectorImageVisual::Action::STOP;
400       break;
401     }
402     case DevelAnimatedVectorImageVisual::Action::JUMP_TO:
403     {
404       int32_t frameNumber;
405       if( attributes.Get( frameNumber ) )
406       {
407         mVectorRasterizeThread.SetCurrentFrameNumber( frameNumber );
408
409         if( IsOnStage() && mVectorRasterizeThread.GetPlayState() != DevelImageVisual::PlayState::PLAYING )
410         {
411           mVectorRasterizeThread.RenderFrame();
412           Stage::GetCurrent().KeepRendering( 0.0f );    // Trigger rendering
413         }
414       }
415       break;
416     }
417     case DevelAnimatedVectorImageVisual::Action::UPDATE_PROPERTY:
418     {
419       Property::Map* map = attributes.GetMap();
420       if( map )
421       {
422         DoSetProperties( *map );
423
424         SendAnimationData();
425       }
426       break;
427     }
428   }
429 }
430
431 void AnimatedVectorImageVisual::OnUploadCompleted()
432 {
433   // If weak handle is holding a placement actor, it is the time to add the renderer to actor.
434   Actor actor = mPlacementActor.GetHandle();
435   if( actor && !mRendererAdded )
436   {
437     actor.AddRenderer( mImpl->mRenderer );
438     mRendererAdded = true;
439   }
440
441   ResourceReady( Toolkit::Visual::ResourceStatus::READY );
442
443   DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnUploadCompleted: Renderer is added [%p]\n", this );
444 }
445
446 void AnimatedVectorImageVisual::OnAnimationFinished()
447 {
448   if( mImpl->mEventObserver )
449   {
450     mImpl->mEventObserver->NotifyVisualEvent( *this, DevelAnimatedVectorImageVisual::Signal::ANIMATION_FINISHED );
451   }
452
453   mActionStatus = DevelAnimatedVectorImageVisual::Action::STOP;
454
455   if( mImpl->mRenderer )
456   {
457     mImpl->mRenderer.SetProperty( DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::IF_REQUIRED );
458   }
459 }
460
461 void AnimatedVectorImageVisual::SendAnimationData()
462 {
463   if( mResendFlag )
464   {
465     bool isPlaying = false;
466     if( mVectorRasterizeThread.GetPlayState() == DevelImageVisual::PlayState::PLAYING )
467     {
468       mVectorRasterizeThread.PauseAnimation();
469       isPlaying = true;
470     }
471
472     if( mResendFlag & RESEND_LOOP_COUNT )
473     {
474       mVectorRasterizeThread.SetLoopCount( mLoopCount );
475     }
476
477     if( mResendFlag & RESEND_PLAY_RANGE )
478     {
479       mVectorRasterizeThread.SetPlayRange( mStartFrame, mEndFrame );
480     }
481
482     if( mResendFlag & RESEND_STOP_BEHAVIOR )
483     {
484       mVectorRasterizeThread.SetStopBehavior( mStopBehavior );
485     }
486
487     if( mResendFlag & RESEND_LOOPING_MODE )
488     {
489       mVectorRasterizeThread.SetLoopingMode( mLoopingMode );
490     }
491
492     if( IsOnStage() )
493     {
494       if( isPlaying )
495       {
496         mVectorRasterizeThread.PlayAnimation();
497       }
498       else
499       {
500         mVectorRasterizeThread.RenderFrame();
501         Stage::GetCurrent().KeepRendering( 0.0f );
502       }
503     }
504
505     mResendFlag = 0;
506   }
507 }
508
509 void AnimatedVectorImageVisual::SetVectorImageSize()
510 {
511   uint32_t width = static_cast< uint32_t >( mVisualSize.width * mVisualScale.width );
512   uint32_t height = static_cast< uint32_t >( mVisualSize.height * mVisualScale.height );
513
514   mVectorRasterizeThread.SetSize( width, height );
515
516   if( IsOnStage() && mVectorRasterizeThread.GetPlayState() != DevelImageVisual::PlayState::PLAYING )
517   {
518     mVectorRasterizeThread.RenderFrame();
519     Stage::GetCurrent().KeepRendering( 0.0f );    // Trigger rendering
520   }
521 }
522
523 void AnimatedVectorImageVisual::OnScaleNotification( PropertyNotification& source )
524 {
525   Actor actor = mPlacementActor.GetHandle();
526   if( actor )
527   {
528     Vector3 scale = actor.GetProperty< Vector3 >( Actor::Property::WORLD_SCALE );
529     mVisualScale.width = scale.width;
530     mVisualScale.height = scale.height;
531
532     DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnScaleNotification: scale = %f, %f [%p]\n", mVisualScale.width, mVisualScale.height, this );
533
534     SetVectorImageSize();
535   }
536 }
537
538 void AnimatedVectorImageVisual::OnSizeNotification( PropertyNotification& source )
539 {
540   Actor actor = mPlacementActor.GetHandle();
541   if( actor )
542   {
543     Vector3 size = actor.GetCurrentSize();
544     mVisualSize.width = size.width;
545     mVisualSize.height = size.height;
546
547     DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnSizeNotification: size = %f, %f [%p]\n", mVisualSize.width, mVisualSize.height, this );
548
549     SetVectorImageSize();
550   }
551 }
552
553 } // namespace Internal
554
555 } // namespace Toolkit
556
557 } // namespace Dali