Merge remote-tracking branch 'origin/tizen' into devel/new_mesh
[platform/core/uifw/dali-demo.git] / examples / motion-stretch / motion-stretch-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 #include <sstream>
19 #include <iomanip>
20
21 #include "shared/view.h"
22 #include <dali/dali.h>
23 #include <dali-toolkit/dali-toolkit.h>
24 #include <dali-toolkit/devel-api/shader-effects/motion-stretch-effect.h>
25
26 using namespace Dali;
27 using namespace Dali::Toolkit;
28
29
30
31 namespace // unnamed namespace
32 {
33
34 ////////////////////////////////////////////////////
35 //
36 // Demo setup parameters
37 //
38
39 const float MOTION_STRETCH_ACTOR_WIDTH = 256;                                          // actor size on screen
40 const float MOTION_STRETCH_ACTOR_HEIGHT = 256;                                         // ""
41
42 const int MOTION_STRETCH_NUM_ACTOR_IMAGES = 5;
43 const char* MOTION_STRETCH_ACTOR_IMAGE1( DALI_IMAGE_DIR "image-with-border-1.jpg" );
44 const char* MOTION_STRETCH_ACTOR_IMAGE2( DALI_IMAGE_DIR "image-with-border-2.jpg" );
45 const char* MOTION_STRETCH_ACTOR_IMAGE3( DALI_IMAGE_DIR "image-with-border-3.jpg" );
46 const char* MOTION_STRETCH_ACTOR_IMAGE4( DALI_IMAGE_DIR "image-with-border-4.jpg" );
47 const char* MOTION_STRETCH_ACTOR_IMAGE5( DALI_IMAGE_DIR "image-with-border-5.jpg" );
48
49 const char* MOTION_STRETCH_ACTOR_IMAGES[] = {
50   MOTION_STRETCH_ACTOR_IMAGE1,
51   MOTION_STRETCH_ACTOR_IMAGE2,
52   MOTION_STRETCH_ACTOR_IMAGE3,
53   MOTION_STRETCH_ACTOR_IMAGE4,
54   MOTION_STRETCH_ACTOR_IMAGE5,
55 };
56
57 const int NUM_ACTOR_ANIMATIONS = 4;
58 const int NUM_CAMERA_ANIMATIONS = 2;
59
60
61 const char* BACKGROUND_IMAGE_PATH = DALI_IMAGE_DIR "background-default.png";
62
63 const char* TOOLBAR_IMAGE( DALI_IMAGE_DIR "top-bar.png" );
64 const char* LAYOUT_IMAGE( DALI_IMAGE_DIR "icon-change.png" );
65 const char* APPLICATION_TITLE( "Motion Stretch" );
66 const char* EFFECTS_OFF_ICON( DALI_IMAGE_DIR "icon-effects-off.png" );
67 const char* EFFECTS_ON_ICON( DALI_IMAGE_DIR "icon-effects-on.png" );
68
69 // These values depend on the button background image
70 const Vector4 BUTTON_IMAGE_BORDER( Vector4::ONE * 3.0f );
71
72 const float UI_MARGIN = 4.0f;                              ///< Screen Margin for placement of UI buttons
73
74 const Vector3 BUTTON_SIZE_CONSTRAINT( 0.24f, 0.09f, 1.0f );
75
76 // move this button down a bit so it is visible on target and not covered up by toolbar
77 const float BUTTON_TITLE_LABEL_Y_OFFSET = 0.05f;
78
79 const float ORIENTATION_DURATION = 0.5f;                  ///< Time to rotate to new orientation.
80 } // unnamed namespace
81
82
83
84
85 //
86 class MotionStretchExampleApp : public ConnectionTracker
87 {
88 public:
89
90   /**
91      * DeviceOrientation describes the four different
92      * orientations the device can be in based on accelerometer reports.
93      */
94   enum DeviceOrientation
95   {
96     PORTRAIT = 0,
97     LANDSCAPE = 90,
98     PORTRAIT_INVERSE = 180,
99     LANDSCAPE_INVERSE = 270
100   };
101
102   /**
103    * Constructor
104    * @param application class, stored as reference
105    */
106   MotionStretchExampleApp(Application &app)
107   : mApplication(app),
108     mActorEffectsEnabled(false),
109     mCurrentActorAnimation(0),
110     mCurrentImage(0)
111   {
112     // Connect to the Application's Init signal
113     app.InitSignal().Connect(this, &MotionStretchExampleApp::OnInit);
114   }
115
116   ~MotionStretchExampleApp()
117   {
118     // Nothing to do here; everything gets deleted automatically
119   }
120
121   /**
122    * This method gets called once the main loop of application is up and running
123    */
124   void OnInit(Application& app)
125   {
126     // The Init signal is received once (only) during the Application lifetime
127
128     Stage::GetCurrent().KeyEventSignal().Connect(this, &MotionStretchExampleApp::OnKeyEvent);
129
130     // Creates a default view with a default tool bar.
131     // The view is added to the stage.
132     mContentLayer = DemoHelper::CreateView( mApplication,
133                                             mView,
134                                             mToolBar,
135                                             BACKGROUND_IMAGE_PATH,
136                                             TOOLBAR_IMAGE,
137                                             APPLICATION_TITLE );
138
139     //Add an slideshow icon on the right of the title
140     mIconEffectsOff = ResourceImage::New( EFFECTS_OFF_ICON );
141     mIconEffectsOn = ResourceImage::New( EFFECTS_ON_ICON );
142     mActorEffectsButton = Toolkit::PushButton::New();
143     mActorEffectsButton.SetBackgroundImage( mIconEffectsOff );
144     mActorEffectsButton.ClickedSignal().Connect( this, &MotionStretchExampleApp::OnEffectButtonClicked );
145     mToolBar.AddControl( mActorEffectsButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalCenter, DemoHelper::DEFAULT_PLAY_PADDING );
146
147     // Creates a mode button.
148     // Create a effect toggle button. (right of toolbar)
149     Image imageLayout = ResourceImage::New( LAYOUT_IMAGE );
150     Toolkit::PushButton layoutButton = Toolkit::PushButton::New();
151     layoutButton.SetBackgroundImage(imageLayout);
152     layoutButton.ClickedSignal().Connect( this, &MotionStretchExampleApp::OnLayoutButtonClicked);
153     layoutButton.SetLeaveRequired( true );
154     mToolBar.AddControl( layoutButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalRight, DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
155
156     // Input
157     mTapGestureDetector = TapGestureDetector::New();
158     mTapGestureDetector.Attach( mContentLayer );
159     mTapGestureDetector.DetectedSignal().Connect( this, &MotionStretchExampleApp::OnTap );
160
161     // set initial orientation
162     Dali::Window winHandle = app.GetWindow();
163     winHandle.AddAvailableOrientation( Dali::Window::PORTRAIT );
164     winHandle.AddAvailableOrientation( Dali::Window::LANDSCAPE );
165     winHandle.AddAvailableOrientation( Dali::Window::PORTRAIT_INVERSE  );
166     winHandle.AddAvailableOrientation( Dali::Window::LANDSCAPE_INVERSE );
167
168    // winHandle.GetOrientation().ChangedSignal().Connect( this, &MotionStretchExampleApp::OnOrientationChanged );
169     unsigned int degrees = 0;
170     Rotate( static_cast< DeviceOrientation >( degrees ) );
171
172
173     ///////////////////////////////////////////////////////
174     //
175     // Motion stretched actor
176     //
177
178     Image image = ResourceImage::New( MOTION_STRETCH_ACTOR_IMAGE1 );
179     mMotionStretchImageActor = ImageActor::New(image);
180     mMotionStretchImageActor.SetParentOrigin( ParentOrigin::CENTER );
181     mMotionStretchImageActor.SetAnchorPoint( AnchorPoint::CENTER );
182     mMotionStretchImageActor.SetSize(MOTION_STRETCH_ACTOR_WIDTH, MOTION_STRETCH_ACTOR_HEIGHT);
183
184     mContentLayer.Add( mMotionStretchImageActor );
185
186     // Create shader used for doing motion stretch
187     mMotionStretchEffect = Toolkit::CreateMotionStretchEffect();
188     Dali::Property::Index uModelProperty = mMotionStretchEffect.GetPropertyIndex( "uModelLastFrame" );
189     Constraint constraint = Constraint::New<Matrix>( mMotionStretchEffect, uModelProperty, EqualToConstraint() );
190     constraint.AddSource( Source( mMotionStretchImageActor , Actor::Property::WORLD_MATRIX ) );
191     constraint.Apply();
192     mMotionStretchImageActor.SetShaderEffect( mMotionStretchEffect );
193   }
194
195   //////////////////////////////////////////////////////////////
196   //
197   // Device Orientation Support
198   //
199   //
200
201   void OnOrientationChanged( Orientation orientation )
202   {
203     unsigned int degrees = orientation.GetDegrees();
204     Rotate( static_cast< DeviceOrientation >( degrees ) );
205   }
206
207   void Rotate( DeviceOrientation orientation )
208   {
209     // Resize the root actor
210     Vector2 stageSize = Stage::GetCurrent().GetSize();
211     Vector2 targetSize = stageSize;
212     if( orientation == LANDSCAPE ||
213         orientation == LANDSCAPE_INVERSE )
214     {
215       targetSize = Vector2( stageSize.y, stageSize.x );
216     }
217
218     if( mOrientation != orientation )
219     {
220       mOrientation = orientation;
221
222       // check if actor is on stage
223       if( mView.GetParent() )
224       {
225         // has parent so we expect it to be on stage, start animation
226         mRotateAnimation = Animation::New( ORIENTATION_DURATION );
227         mRotateAnimation.AnimateTo( Property( mView, Actor::Property::ORIENTATION ), Quaternion( Radian( Degree( -orientation ) ), Vector3::ZAXIS ), AlphaFunction::EASE_OUT );
228         mRotateAnimation.AnimateTo( Property( mView, Actor::Property::SIZE_WIDTH ), targetSize.width );
229         mRotateAnimation.AnimateTo( Property( mView, Actor::Property::SIZE_HEIGHT ), targetSize.height );
230         mRotateAnimation.Play();
231       }
232       else
233       {
234         // set the rotation to match the orientation
235         mView.SetOrientation( Degree( -orientation ), Vector3::ZAXIS );
236         mView.SetSize( targetSize );
237       }
238     }
239     else
240     {
241       // for first time just set size
242       mView.SetSize( targetSize );
243     }
244   }
245
246   //////////////////////////////////////////////////////////////
247   //
248   // Actor Animation
249   //
250   //
251
252   // move to point on screen that was tapped
253   void OnTap( Actor actor, const TapGesture& tapGesture )
254   {
255     Vector3 destPos;
256     float originOffsetX, originOffsetY;
257
258     // rotate offset (from top left origin to centre) into actor space
259     Vector2 stageSize = Dali::Stage::GetCurrent().GetSize();
260     actor.ScreenToLocal(originOffsetX, originOffsetY, stageSize.width * 0.5f, stageSize.height * 0.5f);
261
262     // get dest point in local actor space
263     destPos.x = tapGesture.localPoint.x - originOffsetX;
264     destPos.y = tapGesture.localPoint.y - originOffsetY;
265     destPos.z = 0.0f;
266
267     float animDuration = 0.5f;
268     mActorTapMovementAnimation = Animation::New( animDuration );
269     if ( mMotionStretchImageActor )
270     {
271       mActorTapMovementAnimation.AnimateTo( Property(mMotionStretchImageActor, Actor::Property::POSITION), destPos, AlphaFunction::EASE_IN_OUT_SINE, TimePeriod(animDuration) );
272     }
273     mActorTapMovementAnimation.SetEndAction( Animation::Bake );
274     mActorTapMovementAnimation.Play();
275
276
277     // perform some spinning etc
278     if(mActorEffectsEnabled)
279     {
280       switch(mCurrentActorAnimation)
281       {
282         // spin around y
283         case 0:
284         {
285           float animDuration = 1.0f;
286           mActorAnimation = Animation::New(animDuration);
287           mActorAnimation.AnimateBy( Property( mMotionStretchImageActor, Actor::Property::ORIENTATION ), Quaternion( Radian( Degree(360.0f) ), Vector3::YAXIS ), AlphaFunction::EASE_IN_OUT );
288           mActorAnimation.SetEndAction( Animation::Bake );
289           mActorAnimation.Play();
290         }
291         break;
292
293         // spin around z
294         case 1:
295         {
296           float animDuration = 1.0f;
297           mActorAnimation = Animation::New(animDuration);
298           mActorAnimation.AnimateBy( Property( mMotionStretchImageActor, Actor::Property::ORIENTATION ), Quaternion( Radian( Degree(360.0f) ), Vector3::ZAXIS ), AlphaFunction::EASE_IN_OUT );
299           mActorAnimation.SetEndAction( Animation::Bake );
300           mActorAnimation.Play();
301         }
302         break;
303
304         // spin around y and z
305         case 2:
306         {
307           float animDuration = 1.0f;
308           mActorAnimation = Animation::New(animDuration);
309           mActorAnimation.AnimateBy( Property( mMotionStretchImageActor, Actor::Property::ORIENTATION ), Quaternion( Radian( Degree(360.0f) ), Vector3::YAXIS ), AlphaFunction::EASE_IN_OUT );
310           mActorAnimation.AnimateBy( Property( mMotionStretchImageActor, Actor::Property::ORIENTATION ), Quaternion( Radian( Degree(360.0f) ), Vector3::ZAXIS ), AlphaFunction::EASE_IN_OUT );
311           mActorAnimation.SetEndAction( Animation::Bake );
312           mActorAnimation.Play();
313         }
314         break;
315
316         // scale
317         case 3:
318         {
319           float animDuration = 1.0f;
320           mActorAnimation = Animation::New(animDuration);
321           mActorAnimation.AnimateBy( Property( mMotionStretchImageActor, Actor::Property::SCALE ), Vector3(2.0f, 2.0f, 2.0f), AlphaFunction::BOUNCE, TimePeriod( 0.0f, 1.0f ) );
322           mActorAnimation.SetEndAction( Animation::Bake );
323           mActorAnimation.Play();
324         }
325         break;
326
327         default:
328           break;
329       }
330
331       mCurrentActorAnimation++;
332       if(NUM_ACTOR_ANIMATIONS == mCurrentActorAnimation)
333       {
334         mCurrentActorAnimation = 0;
335       }
336     }
337   }
338
339   void ToggleActorEffects()
340   {
341     if(!mActorEffectsEnabled)
342     {
343       mActorEffectsEnabled = true;
344       mActorEffectsButton.SetBackgroundImage( mIconEffectsOn );
345     }
346     else
347     {
348       mActorEffectsEnabled = false;
349       mActorEffectsButton.SetBackgroundImage( mIconEffectsOff );
350     }
351   }
352
353   //////////////////////////////////////////////////////////////
354   //
355   // Input handlers
356   //
357   //
358
359   bool OnLayoutButtonClicked( Toolkit::Button button )
360   {
361     ChangeImage();
362     return true;
363   }
364
365   bool OnEffectButtonClicked( Toolkit::Button button )
366   {
367     ToggleActorEffects();
368     return true;
369   }
370
371   /**
372    * Main key event handler
373    */
374   void OnKeyEvent(const KeyEvent& event)
375   {
376     if(event.state == KeyEvent::Down)
377     {
378       if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
379       {
380         mApplication.Quit();
381       }
382     }
383   }
384
385   //////////////////////////////////////////////////////////////
386   //
387   // Misc
388   //
389   //
390
391
392   void ChangeImage()
393   {
394     mCurrentImage++;
395     if(MOTION_STRETCH_NUM_ACTOR_IMAGES == mCurrentImage)
396     {
397       mCurrentImage = 0;
398     }
399
400     Image stretchImage = ResourceImage::New( MOTION_STRETCH_ACTOR_IMAGES[mCurrentImage] );
401     mMotionStretchImageActor.SetImage(stretchImage);
402   }
403
404
405 private:
406   Application&               mApplication;            ///< Application instance
407   Toolkit::Control           mView;
408   Toolkit::ToolBar           mToolBar;
409   Image                      mIconEffectsOff;
410   Image                      mIconEffectsOn;
411   Layer                      mContentLayer;           ///< Content layer (contains actor for this stretch demo)
412
413   PushButton                 mActorEffectsButton;     ///< The actor effects toggling Button.
414
415   // Motion stretch
416   ShaderEffect mMotionStretchEffect;
417   ImageActor mMotionStretchImageActor;
418
419   // animate actor to position where user taps screen
420   Animation mActorTapMovementAnimation;
421
422   // show different animations to demonstrate stretch effect working on an object only movement basis
423   bool mActorEffectsEnabled;
424   Animation mActorAnimation;
425   int mCurrentActorAnimation;
426
427   // offer a selection of images that user can cycle between
428   int mCurrentImage;
429
430   TapGestureDetector mTapGestureDetector;
431
432   DeviceOrientation mOrientation;               ///< Current Device orientation
433   Animation mRotateAnimation;                   ///< Animation for rotating between landscape and portrait.
434
435 };
436
437 void RunTest(Application& app)
438 {
439   MotionStretchExampleApp test(app);
440
441   app.MainLoop();
442 }
443
444 // Entry point for Linux & Tizen applications
445 //
446 int main(int argc, char **argv)
447 {
448   Application app = Application::New(&argc, &argv, DALI_DEMO_THEME_PATH);
449
450   RunTest(app);
451
452   return 0;
453 }