de6b3802f2bf5f4fbbdd7485cc189108f572c6a7
[platform/core/uifw/dali-toolkit.git] / base / dali-toolkit / internal / builder / builder-animations.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 <dali/integration-api/debug.h>
20
21 // INTERNAL INCLUDES
22 #include <dali-toolkit/internal/builder/builder-impl.h>
23 #include <dali-toolkit/internal/builder/builder-get-is.inl.h>
24 #include <dali-toolkit/internal/builder/replacement.h>
25
26 namespace // unnamed namespace
27 {
28
29 using namespace Dali;
30
31 TimePeriod GetTimePeriod( const TreeNode& child, const Toolkit::Internal::Replacement& constant )
32 {
33   OptionalFloat delay      = constant.IsFloat( IsChild(child, "delay" ) );
34   OptionalFloat duration   = constant.IsFloat( IsChild(child, "duration" ) );
35   DALI_ASSERT_ALWAYS( duration && "Time period must have at least a duration" );
36
37   if( delay )
38   {
39     return TimePeriod( *delay, *duration );
40   }
41   else
42   {
43     return TimePeriod( *duration );
44   }
45 }
46
47 Property::Value GetPropertyValue( const Property::Type& propType, const TreeNode& child )
48 {
49   switch ( propType )
50   {
51     case Property::BOOLEAN:
52     {
53       return Property::Value( GetBoolean( child ) );
54     }
55
56     case Property::FLOAT:
57     {
58       return Property::Value( GetFloat( child ) );
59     }
60
61     case Property::VECTOR2:
62     {
63       return Property::Value( GetVector2( child ) );
64     }
65
66     case Property::VECTOR3:
67     {
68       return Property::Value( GetVector3( child ) );
69     }
70
71     case Property::VECTOR4:
72     {
73       return Property::Value( GetVector4( child ) );
74     }
75
76     case Property::ROTATION:
77     {
78       if( 4 == child.Size() )
79       {
80         Vector4 v(GetVector4(child));
81         // angle, axis as per spec
82         return Property::Value( Quaternion(Radian(Degree(v[3])),
83                                            Vector3(v[0],v[1],v[2])) );
84       }
85       else
86       {
87         // degrees as per spec
88         Vector3 rotation = GetVector3( child );
89         return Property::Value( Quaternion(Radian(Degree(rotation.x)),
90                                            Radian(Degree(rotation.y)),
91                                            Radian(Degree(rotation.z))) );
92       }
93     }
94
95     case Property::NONE: // fall
96     default:
97     {
98       DALI_ASSERT_ALWAYS( !"Property type incorrect" );
99       return Property::Value();
100     }
101   }
102 }
103
104 AlphaFunction GetAlphaFunction( const std::string& alphaFunction )
105 {
106   typedef std::map< const std::string, Dali::AlphaFunction > AlphaFunctionLut;
107   static AlphaFunctionLut alphaFunctionLut;
108
109   if( 0 == alphaFunctionLut.size() )
110   {
111     // coding convention is uppercase enums
112     alphaFunctionLut["DEFAULT"]                    = AlphaFunctions::Default;
113     alphaFunctionLut["LINEAR"]                     = AlphaFunctions::Linear;
114     alphaFunctionLut["SQUARE"]                     = AlphaFunctions::Square;
115     alphaFunctionLut["REVERSE"]                    = AlphaFunctions::Reverse;
116     alphaFunctionLut["EASE_IN"]                    = AlphaFunctions::EaseIn;
117     alphaFunctionLut["EASE_OUT"]                   = AlphaFunctions::EaseOut;
118     alphaFunctionLut["EASE_IN_OUT"]                = AlphaFunctions::EaseInOut;
119     alphaFunctionLut["EASE_IN_SINE"]               = AlphaFunctions::EaseInSine;
120     alphaFunctionLut["EASE_OUT_SINE"]              = AlphaFunctions::EaseOutSine;
121     alphaFunctionLut["EASE_IN_OUT_SINE"]           = AlphaFunctions::EaseInOutSine;
122     alphaFunctionLut["EASE_IN_SINE_33"]            = AlphaFunctions::EaseInSine33;
123     alphaFunctionLut["EASE_OUT_SINE_33"]           = AlphaFunctions::EaseOutSine33;
124     alphaFunctionLut["EASE_IN_OUT_SINE_33"]        = AlphaFunctions::EaseInOutSine33;
125     alphaFunctionLut["EASE_IN_OUT_SINE_50"]        = AlphaFunctions::EaseInOutSine50;
126     alphaFunctionLut["EASE_IN_OUT_SINE_60"]        = AlphaFunctions::EaseInOutSine60;
127     alphaFunctionLut["EASE_IN_OUT_SINE_70"]        = AlphaFunctions::EaseInOutSine70;
128     alphaFunctionLut["EASE_IN_OUT_SINE_80"]        = AlphaFunctions::EaseInOutSine80;
129     alphaFunctionLut["EASE_IN_OUT_SINE_90"]        = AlphaFunctions::EaseInOutSine90;
130     alphaFunctionLut["DOUBLE_EASE_IN_OUT_SINE_60"] = AlphaFunctions::DoubleEaseInOutSine60;
131     alphaFunctionLut["EASE_OUT_QUINT_50"]          = AlphaFunctions::EaseOutQuint50;
132     alphaFunctionLut["EASE_OUT_QUINT_80"]          = AlphaFunctions::EaseOutQuint80;
133     alphaFunctionLut["BOUNCE"]                     = AlphaFunctions::Bounce;
134     alphaFunctionLut["BOUNCE_BACK"]                = AlphaFunctions::BounceBack;
135     alphaFunctionLut["EASE_IN_BACK"]               = AlphaFunctions::EaseInBack;
136     alphaFunctionLut["EASE_OUT_BACK"]              = AlphaFunctions::EaseOutBack;
137     alphaFunctionLut["EASE_IN_OUT_BACK"]           = AlphaFunctions::EaseInOutBack;
138     alphaFunctionLut["SIN"]                        = AlphaFunctions::Sin;
139     alphaFunctionLut["SIN2X"]                      = AlphaFunctions::Sin2x;
140   }
141
142   const AlphaFunctionLut::const_iterator iter( alphaFunctionLut.find( alphaFunction ) );
143
144   if( iter != alphaFunctionLut.end() )
145   {
146     return iter->second;
147   }
148   else
149   {
150     DALI_ASSERT_ALWAYS( iter != alphaFunctionLut.end() && "Unknown Anchor Constant" );
151     return Dali::AlphaFunctions::Default;
152   }
153 }
154
155 } // unnamed namespace
156
157
158 namespace Dali
159 {
160
161 namespace Toolkit
162 {
163
164 namespace Internal
165 {
166
167 Animation CreateAnimation( const TreeNode& child, const Replacement& constant, Dali::Actor searchRoot )
168 {
169   float durationSum = 0.f;
170
171   Dali::Actor searchActor = searchRoot ? searchRoot : Dali::Stage::GetCurrent().GetRootLayer();
172
173   Animation animation( Animation::New( 0.f ) );
174
175   // duration needs to be set before AnimateTo calls for correct operation when AnimateTo has no "time-period".
176   OptionalFloat duration = constant.IsFloat( IsChild(child, "duration" ) );
177
178   if( duration )
179   {
180     animation.SetDuration( *duration );
181   }
182
183   if( OptionalBoolean looping = constant.IsBoolean(  IsChild(child, "loop" ) ) )
184   {
185     animation.SetLooping( *looping );
186   }
187
188   if( OptionalString endAction = constant.IsString(  IsChild(child, "end-action" ) ) )
189   {
190     if("BAKE" == *endAction)
191     {
192       animation.SetEndAction( Animation::Bake );
193     }
194     else if("DISCARD" == *endAction)
195     {
196       animation.SetEndAction( Animation::Discard );
197     }
198     else if("BAKE_FINAL" == *endAction)
199     {
200       animation.SetEndAction( Animation::BakeFinal );
201     }
202   }
203
204   if( OptionalString endAction = constant.IsString(  IsChild(child, "disconnect-action" ) ) )
205   {
206     if("BAKE" == *endAction)
207     {
208       animation.SetDisconnectAction( Animation::Bake );
209     }
210     else if("DISCARD" == *endAction)
211     {
212       animation.SetDisconnectAction( Animation::Discard );
213     }
214     else if("BAKE_FINAL" == *endAction)
215     {
216       animation.SetDisconnectAction( Animation::BakeFinal );
217     }
218   }
219
220   OptionalChild propertiesNode = IsChild(child, "properties" );
221   if(propertiesNode)
222   {
223     const TreeNode::ConstIterator endIter = (*propertiesNode).CEnd();
224     for( TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter )
225     {
226       const TreeNode::KeyNodePair& pKeyChild = *iter;
227
228       OptionalString actorName( constant.IsString( IsChild(pKeyChild.second, "actor" ) ) );
229       OptionalString property(  constant.IsString( IsChild(pKeyChild.second, "property" ) ) );
230       DALI_ASSERT_ALWAYS( actorName && "Animation must specify actor name" );
231       DALI_ASSERT_ALWAYS( property  && "Animation must specify a property name" );
232
233       Handle targetHandle = searchActor.FindChildByName( *actorName );
234       DALI_ASSERT_ALWAYS( targetHandle && "Actor must exist for property" );
235
236       Property::Index idx( targetHandle.GetPropertyIndex( *property ) );
237
238       // if the property is not found from the (actor) handle, try to downcast it to renderable actor
239       // to allow animating shader uniforms
240       if( idx == Property::INVALID_INDEX )
241       {
242         RenderableActor renderable = RenderableActor::DownCast( targetHandle );
243         if( renderable )
244         {
245           // A limitation here is that its possible that between creation of animation
246           // and running it the ShaderEffect of the actor has been changed.
247           // However this is a unlikely use case especially when using scripts.
248           if( ShaderEffect effect = renderable.GetShaderEffect() )
249           {
250             idx = effect.GetPropertyIndex( *property );
251             if(idx != Property::INVALID_INDEX)
252             {
253               targetHandle = effect;
254             }
255             else
256             {
257               DALI_SCRIPT_WARNING( "Cannot find property on object or ShaderEffect\n" );
258               continue;
259             }
260           }
261         }
262         else
263         {
264           DALI_SCRIPT_WARNING( "Cannot find property on object or ShaderEffect\n" );
265           continue;
266         }
267       }
268
269       if( idx == Property::INVALID_INDEX)
270       {
271         DALI_ASSERT_ALWAYS( idx != Property::INVALID_INDEX && "Animation must specify a valid property" );
272         continue;
273       }
274
275       Property prop( Property( targetHandle, idx ) );
276       Property::Value propValue;
277
278       // these are the defaults
279       AlphaFunction alphaFunction( AlphaFunctions::Default );
280       TimePeriod timePeriod( 0.f );
281
282       OptionalChild timeChild = IsChild( pKeyChild.second, "time-period" );
283
284       if( timeChild )
285       {
286         timePeriod = GetTimePeriod( *timeChild, constant );
287       }
288
289       durationSum = std::max( durationSum, timePeriod.delaySeconds + timePeriod.durationSeconds );
290
291       if( OptionalString alphaChild = constant.IsString( IsChild(pKeyChild.second, "alpha-function" ) ) )
292       {
293         alphaFunction = GetAlphaFunction( *alphaChild );
294       }
295
296       if( OptionalChild keyFrameChild = IsChild(pKeyChild.second, "key-frames") )
297       {
298         KeyFrames keyframes = KeyFrames::New();
299
300         const TreeNode::ConstIterator endIter = (*keyFrameChild).CEnd();
301         for( TreeNode::ConstIterator iter = (*keyFrameChild).CBegin(); endIter != iter; ++iter )
302         {
303           const TreeNode::KeyNodePair& kfKeyChild = *iter;
304
305           OptionalFloat kfProgress = constant.IsFloat( IsChild(kfKeyChild.second, "progress" ) );
306           DALI_ASSERT_ALWAYS( kfProgress && "Key frame entry must have 'progress'" );
307
308           OptionalChild kfValue = IsChild( kfKeyChild.second, "value" );
309           DALI_ASSERT_ALWAYS( kfValue && "Key frame entry must have 'value'" );
310
311           try
312           {
313             propValue = GetPropertyValue( prop.object.GetPropertyType(prop.propertyIndex), *kfValue );
314           }
315           catch(...)
316           {
317             DALI_LOG_WARNING( "Property:'%s' type does not match value type '%s'\n",
318                               (*property).c_str(),
319                               PropertyTypes::GetName(prop.object.GetPropertyType(prop.propertyIndex)) );
320
321             throw;
322           }
323
324           AlphaFunction kfAlphaFunction( AlphaFunctions::Default );
325           if( OptionalString alphaFuncStr = constant.IsString( IsChild(pKeyChild.second, "alpha-function") ) )
326           {
327             kfAlphaFunction = GetAlphaFunction( *alphaFuncStr );
328           }
329
330           keyframes.Add( *kfProgress, propValue, kfAlphaFunction );
331         }
332
333         if( timeChild )
334         {
335           animation.AnimateBetween( prop, keyframes, alphaFunction, timePeriod );
336         }
337         else
338         {
339           animation.AnimateBetween( prop, keyframes, alphaFunction );
340         }
341       }
342       else
343       {
344         try
345         {
346           propValue = GetPropertyValue( prop.object.GetPropertyType(prop.propertyIndex), *IsChild(pKeyChild.second, "value") );
347         }
348         catch(...)
349         {
350           DALI_LOG_WARNING( "Property:'%s' type does not match value type '%s'\n", (*property).c_str(),
351                             PropertyTypes::GetName( prop.object.GetPropertyType(prop.propertyIndex) ) );
352
353           throw;
354         }
355
356         if( OptionalBoolean relative = constant.IsBoolean( IsChild(pKeyChild.second, "relative") ) )
357         {
358           if( timeChild )
359           {
360             animation.AnimateBy( prop, propValue, alphaFunction, timePeriod );
361           }
362           else
363           {
364             animation.AnimateBy( prop, propValue, alphaFunction );
365           }
366         }
367         else
368         {
369           if( timeChild )
370           {
371             animation.AnimateTo( prop, propValue, alphaFunction, timePeriod );
372           }
373           else
374           {
375             animation.AnimateTo( prop, propValue, alphaFunction );
376           }
377         }
378       }
379     }
380   }
381
382   if( !duration )
383   {
384     animation.SetDuration( durationSum );
385   }
386
387   return animation;
388 }
389
390 Animation CreateAnimation( const TreeNode& child )
391 {
392   Replacement replacement;
393   return CreateAnimation( child, replacement, Stage::GetCurrent().GetRootLayer() );
394 }
395
396 } // namespace Internal
397
398 } // namespace Toolkit
399
400 } // namespace Dali
401