Image scaling and filtering on load across all applicable demos
[platform/core/uifw/dali-demo.git] / examples / dissolve-effect / dissolve-effect-example.cpp
1 /*
2  * Copyright (c) 2014 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 // EXTERNAL INCLUDES
19 #include <math.h>
20
21 // INTERNAL INCLUDES
22 #include "shared/view.h"
23
24 #include <dali/dali.h>
25 #include <dali-toolkit/dali-toolkit.h>
26
27 using namespace Dali;
28
29 // LOCAL STUFF
30 namespace
31 {
32
33 const char * const TOOLBAR_IMAGE( DALI_IMAGE_DIR "top-bar.png" );
34 const char * const APPLICATION_TITLE_HIGHP( "Dissolve Effect(highp)" );
35 const char * const APPLICATION_TITLE_MEDIUMP( "Dissolve Effect(mediump)" );
36 const char * const EFFECT_HIGHP_IMAGE( DALI_IMAGE_DIR "icon-highp.png" );
37 const char * const EFFECT_MEDIUMP_IMAGE( DALI_IMAGE_DIR "icon-mediump.png" );
38 const char * const PLAY_ICON( DALI_IMAGE_DIR "icon-play.png" );
39 const char * const STOP_ICON( DALI_IMAGE_DIR "icon-stop.png" );
40
41 const char* IMAGES[] =
42 {
43   DALI_IMAGE_DIR "gallery-large-1.jpg",
44   DALI_IMAGE_DIR "gallery-large-2.jpg",
45   DALI_IMAGE_DIR "gallery-large-3.jpg",
46   DALI_IMAGE_DIR "gallery-large-4.jpg",
47   DALI_IMAGE_DIR "gallery-large-5.jpg",
48   DALI_IMAGE_DIR "gallery-large-6.jpg",
49   DALI_IMAGE_DIR "gallery-large-7.jpg",
50   DALI_IMAGE_DIR "gallery-large-8.jpg",
51   DALI_IMAGE_DIR "gallery-large-9.jpg",
52   DALI_IMAGE_DIR "gallery-large-10.jpg",
53   DALI_IMAGE_DIR "gallery-large-11.jpg",
54   DALI_IMAGE_DIR "gallery-large-12.jpg",
55   DALI_IMAGE_DIR "gallery-large-13.jpg",
56   DALI_IMAGE_DIR "gallery-large-14.jpg",
57   DALI_IMAGE_DIR "gallery-large-15.jpg",
58   DALI_IMAGE_DIR "gallery-large-16.jpg",
59   DALI_IMAGE_DIR "gallery-large-17.jpg",
60   DALI_IMAGE_DIR "gallery-large-18.jpg",
61   DALI_IMAGE_DIR "gallery-large-19.jpg",
62   DALI_IMAGE_DIR "gallery-large-20.jpg",
63   DALI_IMAGE_DIR "gallery-large-21.jpg",
64 };
65
66 const int NUM_IMAGES( sizeof(IMAGES) / sizeof(IMAGES[0]) );
67
68 // The duration of the current image staying on screen when slideshow is on
69 const int VIEWINGTIME = 2000; // 2 seconds
70
71 const float TRANSITION_DURATION = 2.5f; //2.5 second
72
73 const float INITIAL_DEPTH = -10.0f;
74
75 /**
76  * @brief Load an image, scaled-down to no more than the stage dimensions.
77  *
78  * Uses image scaling mode ImageAttributes::ScaleToFill to resize the image at
79  * load time to cover the entire stage with pixels with no borders,
80  * and filter mode ImageAttributes::BoxThenLinear to sample the image with
81  * maximum quality.
82  */
83 ResourceImage LoadStageFillingImage( const char * const imagePath )
84 {
85   Size stageSize = Stage::GetCurrent().GetSize();
86   ImageAttributes attributes;
87   attributes.SetSize( stageSize.x, stageSize.y );
88   attributes.SetFilterMode( ImageAttributes::BoxThenLinear );
89   attributes.SetScalingMode( ImageAttributes::ScaleToFill );
90   return ResourceImage::New( imagePath, attributes );
91 }
92
93 } // namespace
94
95 class DissolveEffectApp : public ConnectionTracker
96 {
97 public:
98
99   /**
100    * Constructor
101    * @param application class, stored as reference
102    */
103   DissolveEffectApp( Application& application );
104
105   ~DissolveEffectApp();
106
107 private:
108
109   /**
110    * This method gets called once the main loop of application is up and running
111    */
112   void OnInit( Application& application );
113   /**
114    * PanGesture callback. This method gets called when the pan gesture is detected.
115    * @param[in] actor The actor receiving the pan gesture.
116    * @param[in] gesture The detected pan gesture.
117    */
118   void OnPanGesture( Actor actor, const PanGesture& gesture );
119
120   /**
121    * Set up the animations for transition
122    * @param[in] position The point ( locates within rectange {(0,0),(0,1),(1,0),(1,1)} ) passing through the central line of the dissolve effect
123    * @param[in] displacement The direction of the central line of the dissolve effect
124    */
125   void StartTransition(Vector2 position, Vector2 displacement);
126   /**
127    * Callback function of effect-switch button
128    * Change the precision of the effect shader when the effect button is clicked
129    * @param[in] button The handle of the clicked button
130    */
131   bool OnEffectButtonClicked( Toolkit::Button button );
132   /**
133    * Callback function of slideshow button
134    * Start or stop the automatical image display when the slideshow button is clicked
135    * @param[in] button The handle of the clicked button
136    */
137   bool OnSildeshowButtonClicked( Toolkit::Button button );
138   /**
139    * Callback function of cube transition completed signal
140    * @param[in] effect The cube effect used for the transition
141    * @param[in] imageActor The target imageActor of the completed transition
142    */
143   void OnTransitionCompleted(Animation& source);
144   /**
145    * Callback function of timer tick
146    * The timer is used to count the image display duration after cube transition in slideshow,
147    */
148   bool OnTimerTick();
149
150   /**
151    * Main key event handler
152    */
153   void OnKeyEvent(const KeyEvent& event);
154
155 private:
156   Application&                    mApplication;
157   Toolkit::View                   mView;
158   Toolkit::ToolBar                mToolBar;
159   Layer                           mContent;
160   Toolkit::TextView               mTitleActor;
161   Actor                           mParent;
162
163   ImageActor                      mCurrentImage;
164   ImageActor                      mNextImage;
165   unsigned int                    mIndex;
166   Constraint                      mSizeConstraint;
167
168   Toolkit::DissolveEffect         mCurrentImageEffect;
169   Toolkit::DissolveEffect         mNextImageEffect;
170   bool                            mUseHighPrecision;
171   Animation                       mAnimation;
172
173   PanGestureDetector              mPanGestureDetector;
174   bool                            mIsTransiting;
175
176   bool                            mSlideshow;
177   Timer                           mViewTimer;
178   bool                            mTimerReady;
179   unsigned int                    mCentralLineIndex;
180
181   Image                           mIconPlay;
182   Image                           mIconStop;
183   Toolkit::PushButton             mPlayStopButton;
184
185   Image                           mIconHighP;
186   Image                           mIconMediumP;
187   Toolkit::PushButton             mEffectChangeButton;
188 };
189
190 DissolveEffectApp::DissolveEffectApp( Application& application )
191 : mApplication( application ),
192   mIndex( 0 ),
193   mUseHighPrecision(true),
194   mIsTransiting( false ),
195   mSlideshow( false ),
196   mTimerReady( false ),
197   mCentralLineIndex( 0 )
198 {
199   mApplication.InitSignal().Connect( this, &DissolveEffectApp::OnInit );
200 }
201
202 DissolveEffectApp::~DissolveEffectApp()
203 {
204   //Nothing to do
205 }
206
207 void DissolveEffectApp::OnInit( Application& application )
208 {
209   Stage::GetCurrent().KeyEventSignal().Connect(this, &DissolveEffectApp::OnKeyEvent);
210
211   // Creates a default view with a default tool bar, the view is added to the stage.
212   mContent = DemoHelper::CreateView( application, mView,mToolBar, "", TOOLBAR_IMAGE, "" );
213
214   // Add an effect-changing button on the right of the tool bar.
215   mIconHighP = ResourceImage::New( EFFECT_HIGHP_IMAGE );
216   mIconMediumP = ResourceImage::New( EFFECT_MEDIUMP_IMAGE );
217   mEffectChangeButton = Toolkit::PushButton::New();
218   mEffectChangeButton.SetBackgroundImage(mIconHighP);
219   mEffectChangeButton.ClickedSignal().Connect( this, &DissolveEffectApp::OnEffectButtonClicked );
220   mToolBar.AddControl( mEffectChangeButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalRight, DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
221
222   // Add title to the tool bar.
223   mTitleActor = Toolkit::TextView::New();
224   mTitleActor.SetText( APPLICATION_TITLE_HIGHP );
225   mTitleActor.SetStyleToCurrentText(DemoHelper::GetDefaultTextStyle());
226   mToolBar.AddControl( mTitleActor, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarTitlePercentage, Toolkit::Alignment::HorizontalCenter );
227
228   // Add an slide-show button on the right of the title
229   mIconPlay = ResourceImage::New( PLAY_ICON );
230   mIconStop = ResourceImage::New( STOP_ICON );
231   mPlayStopButton = Toolkit::PushButton::New();
232   mPlayStopButton.SetBackgroundImage( mIconPlay );
233   mPlayStopButton.ClickedSignal().Connect( this, &DissolveEffectApp::OnSildeshowButtonClicked );
234   mToolBar.AddControl( mPlayStopButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalCenter, DemoHelper::DEFAULT_PLAY_PADDING );
235
236   // use pan gesture to detect the cursor or finger movement
237   mPanGestureDetector = PanGestureDetector::New();
238   mPanGestureDetector.DetectedSignal().Connect( this, &DissolveEffectApp::OnPanGesture );
239
240   // create the dissolve effect object
241   mCurrentImageEffect = Toolkit::DissolveEffect::New(mUseHighPrecision);
242   mNextImageEffect = Toolkit::DissolveEffect::New(mUseHighPrecision);
243
244   mViewTimer = Timer::New( VIEWINGTIME );
245   mViewTimer.TickSignal().Connect( this, &DissolveEffectApp::OnTimerTick );
246   mTimerReady = true;
247
248   // Set size to stage size to avoid seeing a black border on transition
249   mParent = Actor::New();
250   mParent.SetSize( Stage::GetCurrent().GetSize() );
251   mParent.SetPositionInheritanceMode( USE_PARENT_POSITION );
252   mContent.Add( mParent );
253
254   mSizeConstraint= Constraint::New<Vector3>( Actor::Property::SCALE, LocalSource( Actor::Property::SIZE ), ParentSource( Actor::Property::SIZE ), ScaleToFitKeepAspectRatioConstraint() );
255
256   // show the first image
257   mCurrentImage = ImageActor::New( LoadStageFillingImage( IMAGES[mIndex] ) );
258   mCurrentImage.SetPositionInheritanceMode(USE_PARENT_POSITION_PLUS_LOCAL_POSITION);
259   mCurrentImage.ApplyConstraint( mSizeConstraint );
260   mParent.Add( mCurrentImage );
261
262   mPanGestureDetector.Attach( mCurrentImage );
263 }
264
265 // signal handler, called when the pan gesture is detected
266 void DissolveEffectApp::OnPanGesture( Actor actor, const PanGesture& gesture )
267 {
268   // does not response when the animation has not finished
269   if( mIsTransiting || mSlideshow )
270   {
271     return;
272   }
273
274   if( gesture.state == Gesture::Continuing )
275   {
276     if( gesture.displacement.x < 0)
277     {
278       mIndex = (mIndex + 1)%NUM_IMAGES;
279     }
280     else
281     {
282       mIndex = (mIndex + NUM_IMAGES -1)%NUM_IMAGES;
283     }
284
285     Image image = LoadStageFillingImage( IMAGES[ mIndex ] );
286     mNextImage = ImageActor::New( image );
287     mNextImage.SetPositionInheritanceMode(USE_PARENT_POSITION_PLUS_LOCAL_POSITION);
288     mNextImage.ApplyConstraint( mSizeConstraint );
289     mNextImage.SetZ(INITIAL_DEPTH);
290     mParent.Add( mNextImage );
291     Vector2 size = Vector2( mCurrentImage.GetCurrentSize() );
292     StartTransition( gesture.position / size, gesture.displacement * Vector2(1.0, size.x/size.y));
293   }
294 }
295
296 void DissolveEffectApp::StartTransition(Vector2 position, Vector2 displacement)
297 {
298   mAnimation = Animation::New(TRANSITION_DURATION);
299
300   mCurrentImageEffect.SetCentralLine(position,displacement);
301   mCurrentImageEffect.SetDistortion(0.0f);
302   mCurrentImage.SetShaderEffect(mCurrentImageEffect);
303   mAnimation.AnimateTo( Property(mCurrentImageEffect, mCurrentImageEffect.GetDistortionPropertyName()), 1.0f, AlphaFunctions::Linear );
304
305   mNextImage.SetOpacity(0.0f);
306   mAnimation.OpacityTo( mNextImage, 1.0, AlphaFunctions::Linear );
307
308   if(mUseHighPrecision)
309   {
310     mNextImageEffect.SetCentralLine(position,-displacement);
311     mNextImageEffect.SetDistortion(1.0f);
312     mNextImage.SetShaderEffect(mNextImageEffect);
313     mAnimation.AnimateTo( Property(mNextImageEffect, mNextImageEffect.GetDistortionPropertyName()), 0.0f, AlphaFunctions::Linear );
314   }
315   else
316   {
317     mAnimation.MoveTo(mNextImage, Vector3(0.0f, 0.0f, 0.0f), AlphaFunctions::Linear);
318   }
319
320   mAnimation.FinishedSignal().Connect( this, &DissolveEffectApp::OnTransitionCompleted );
321   mAnimation.Play();
322   mIsTransiting = true;
323 }
324
325 void DissolveEffectApp::OnKeyEvent(const KeyEvent& event)
326 {
327   if(event.state == KeyEvent::Down)
328   {
329     if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
330     {
331       mApplication.Quit();
332     }
333   }
334 }
335
336 bool DissolveEffectApp::OnEffectButtonClicked( Toolkit::Button button )
337 {
338   mUseHighPrecision = !mUseHighPrecision;
339   mCurrentImageEffect = Toolkit::DissolveEffect::New(mUseHighPrecision);
340   if(mUseHighPrecision)
341   {
342     mTitleActor.SetText( APPLICATION_TITLE_HIGHP );
343     mEffectChangeButton.SetBackgroundImage(mIconHighP);
344   }
345   else
346   {
347     mTitleActor.SetText( APPLICATION_TITLE_MEDIUMP );
348     mEffectChangeButton.SetBackgroundImage(mIconMediumP);
349   }
350   mTitleActor.SetStyleToCurrentText(DemoHelper::GetDefaultTextStyle());
351
352   return true;
353 }
354
355 bool DissolveEffectApp::OnSildeshowButtonClicked( Toolkit::Button button )
356 {
357   mSlideshow = !mSlideshow;
358   if( mSlideshow )
359   {
360     mPlayStopButton.SetBackgroundImage( mIconStop );
361     mPanGestureDetector.Detach( mParent );
362     mViewTimer.Start();
363     mTimerReady = false;
364   }
365   else
366   {
367     mPlayStopButton.SetBackgroundImage( mIconPlay );
368     mTimerReady = true;
369     mPanGestureDetector.Attach( mParent );
370   }
371   return true;
372 }
373
374 void DissolveEffectApp::OnTransitionCompleted( Animation& source )
375 {
376   mCurrentImage.RemoveShaderEffect();
377   mNextImage.RemoveShaderEffect();
378   mParent.Remove( mCurrentImage );
379   mPanGestureDetector.Detach( mCurrentImage );
380   mCurrentImage = mNextImage;
381   mPanGestureDetector.Attach( mCurrentImage );
382   mIsTransiting = false;
383
384   if( mSlideshow)
385   {
386     mViewTimer.Start();
387     mTimerReady = false;
388   }
389 }
390
391 bool DissolveEffectApp::OnTimerTick()
392 {
393   mTimerReady = true;
394   if(mSlideshow)
395   {
396     mIndex = (mIndex + 1)%NUM_IMAGES;
397     Image image = LoadStageFillingImage( IMAGES[ mIndex ] );
398     mNextImage = ImageActor::New( image );
399     mNextImage.SetPositionInheritanceMode(USE_PARENT_POSITION_PLUS_LOCAL_POSITION);
400     mNextImage.ApplyConstraint( mSizeConstraint );
401     mNextImage.SetZ(INITIAL_DEPTH);
402     mParent.Add( mNextImage );
403     switch( mCentralLineIndex%4 )
404     {
405       case 0:
406       {
407         StartTransition(Vector2(1.0f,0.5f), Vector2(-1.0f, 0.0f));
408         break;
409       }
410       case 1:
411       {
412         StartTransition(Vector2(0.5f,0.0f), Vector2(0.0f, 1.0f));
413         break;
414       }
415       case 2:
416       {
417         StartTransition(Vector2(0.0f,0.5f), Vector2(1.0f, 0.0f));
418         break;
419       }
420       default:
421       {
422         StartTransition(Vector2(0.5f,1.0f), Vector2(0.0f, -1.0f));
423         break;
424       }
425
426     }
427     mCentralLineIndex++;
428   }
429   return false;   //return false to stop the timer
430 }
431
432 // Entry point for Linux & Tizen applications
433 int main( int argc, char **argv )
434 {
435   Application application = Application::New( &argc, &argv );
436   DissolveEffectApp test( application );
437   application.MainLoop();
438
439   return 0;
440 }