Pan Gesture Prediction - Added DALI_PAN_GESTURE_PREDICTION_AMOUNT environment variable
[platform/core/uifw/dali-core.git] / dali / internal / event / events / pan-gesture-processor.cpp
1 //
2 // Copyright (c) 2014 Samsung Electronics Co., Ltd.
3 //
4 // Licensed under the Flora License, Version 1.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://floralicense.org/license/
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 // CLASS HEADER
18 #include <dali/internal/event/events/pan-gesture-processor.h>
19
20 // EXTERNAL INCLUDES
21 #include <algorithm>
22
23 // INTERNAL INCLUDES
24 #include <dali/public-api/actors/actor.h>
25 #include <dali/public-api/common/dali-common.h>
26 #include <dali/public-api/events/pan-gesture.h>
27 #include <dali/public-api/math/vector2.h>
28 #include <dali/integration-api/events/pan-gesture-event.h>
29 #include <dali/integration-api/gesture-manager.h>
30 #include <dali/integration-api/debug.h>
31 #include <dali/internal/event/common/stage-impl.h>
32 #include <dali/internal/event/render-tasks/render-task-impl.h>
33 #include <dali/internal/update/gestures/scene-graph-pan-gesture.h>
34
35 namespace Dali
36 {
37
38 namespace Internal
39 {
40
41 namespace // unnamed namespace
42 {
43
44 const unsigned long MAXIMUM_TIME_WITH_VALID_LAST_VELOCITY( 50u );
45
46 /**
47  * Functor which checks whether the specified actor is attached to the gesture detector.
48  * If the actor is attached, it also checks whether the number of touches of the current pan event
49  * are within the range of that expected by the detector.
50  * It returns true if it is no longer attached or the touches are out of range.
51  * This can be used in remove_if functions.
52  */
53 struct IsNotAttachedAndOutsideTouchesRangeFunctor
54 {
55   /**
56    * Constructor
57    * @param[in]  actor                 The actor to check whether it is attached.
58    * @param[in]  touches               The number of touches in the current pan event.
59    * @param[in]  outsideRangeEmitters  Reference to container where emitters outside of the touches range should be added.
60    */
61   IsNotAttachedAndOutsideTouchesRangeFunctor(Actor* actor, unsigned int touches, PanGestureDetectorContainer& outsideRangeEmitters)
62   : actorToCheck(actor),
63     numberOfTouches(touches),
64     outsideTouchesRangeEmitters(outsideRangeEmitters)
65   {
66   }
67
68   /**
69    * Returns true if not attached, false if it is still attached.
70    * Additionally, checks if the number of touches has changed and stops sending the pan to a particular
71    * detector if it exceeds the range of that detector.
72    * @param[in]  detector  The detector to check.
73    * @return true, if not attached, false otherwise.
74    */
75   bool operator()(PanGestureDetector* detector) const
76   {
77     bool remove(!detector->IsAttached(*actorToCheck));
78
79     if (!remove)
80     {
81       // Ensure number of touch points is within the range of our emitter. If it isn't then remove
82       // this emitter and add it to the outsideTouchesRangeEmitters container
83       if ( (numberOfTouches < detector->GetMinimumTouchesRequired()) ||
84            (numberOfTouches > detector->GetMaximumTouchesRequired()) )
85       {
86         remove = true;
87         outsideTouchesRangeEmitters.push_back(detector);
88       }
89     }
90
91     return remove;
92   }
93
94   Actor* actorToCheck; ///< The actor to check whether it is attached or not.
95   unsigned int numberOfTouches; ///< The number of touches in the pan event.
96   PanGestureDetectorContainer& outsideTouchesRangeEmitters; ///< Emitters that are outside of the range of current pan.
97 };
98
99 } // unnamed namespace
100
101 struct PanGestureProcessor::PanEventFunctor : public GestureProcessor::Functor
102 {
103   /**
104    * Constructor
105    * @param[in]  panEvent   The current gesture event.
106    * @param[in]  processor  Reference to the processor.
107    */
108   PanEventFunctor( const Integration::PanGestureEvent& panEvent, PanGestureProcessor& processor )
109   : panEvent( panEvent ),
110     processor( processor )
111   {
112   }
113
114   /**
115    * Check if the detector meets the current gesture event parameters.
116    */
117   virtual bool operator() ( GestureDetector* detector, Actor* actor )
118   {
119     bool retVal( false );
120
121     PanGestureDetector* panDetector( static_cast< PanGestureDetector* >( detector ) );
122
123     if ( ( panEvent.numberOfTouches >= panDetector->GetMinimumTouchesRequired() ) &&
124          ( panEvent.numberOfTouches <= panDetector->GetMaximumTouchesRequired() ) )
125     {
126       // Check if the detector requires directional panning.
127       if ( panDetector->RequiresDirectionalPan() && processor.mCurrentRenderTask )
128       {
129         // It does, calculate the angle of the pan in local actor coordinates and ensures it fits
130         // the detector's criteria.
131         RenderTask& renderTaskImpl( GetImplementation( processor.mCurrentRenderTask ) );
132
133         Vector2 startPosition, currentPosition;
134         actor->ScreenToLocal( renderTaskImpl, startPosition.x,   startPosition.y,   processor.mPossiblePanPosition.x, processor.mPossiblePanPosition.y );
135         actor->ScreenToLocal( renderTaskImpl, currentPosition.x, currentPosition.y, panEvent.currentPosition.x,       panEvent.currentPosition.y );
136         Vector2 displacement( currentPosition - startPosition );
137
138         Radian angle( atan( displacement.y / displacement.x ) );
139
140         /////////////////////////////
141         //            |            //
142         //            |            //
143         //   Q3 (-,-) | Q4 (+,-)   //
144         //            |            //
145         //    ----------------- +x //
146         //            |            //
147         //   Q2 (-,+) | Q1 (+,+)   //
148         //            |            //
149         //            |            //
150         //           +y            //
151         /////////////////////////////
152         // Quadrant 1: As is
153         // Quadrant 2: 180 degrees + angle
154         // Quadrant 3: angle - 180 degrees
155         // Quadrant 4: As is
156         /////////////////////////////
157
158         if ( displacement.x < 0.0f )
159         {
160           if ( displacement.y >= 0.0f )
161           {
162             // Quadrant 2
163             angle += Math::PI;
164           }
165           else
166           {
167             // Quadrant 3
168             angle -= Math::PI;
169           }
170         }
171
172         if ( panDetector->CheckAngleAllowed( angle ) )
173         {
174           retVal = true;
175         }
176       }
177       else
178       {
179         // Directional panning not required so we can use this actor and gesture detector.
180         retVal = true;
181       }
182     }
183
184     return retVal;
185   }
186
187   /**
188    * Gestured actor and gesture detectors that meet the gesture's parameters found, emit and save required information.
189    */
190   virtual void operator() ( Dali::Actor actor, const GestureDetectorContainer& gestureDetectors, Vector2 actorCoordinates )
191   {
192     PanGestureDetectorContainer derivedContainer;
193     DownCastContainer<PanGestureDetector>( gestureDetectors, derivedContainer );
194
195     processor.mCurrentPanEmitters.clear();
196     processor.ResetActor();
197
198     Actor* actorImpl( &GetImplementation( actor ) );
199     actorImpl->ScreenToLocal( GetImplementation(processor.mCurrentRenderTask), actorCoordinates.x, actorCoordinates.y, panEvent.currentPosition.x, panEvent.currentPosition.y );
200
201     processor.EmitPanSignal( actor, derivedContainer, panEvent, actorCoordinates, panEvent.state, processor.mCurrentRenderTask );
202
203     if ( actorImpl->OnStage() )
204     {
205       processor.mCurrentPanEmitters = derivedContainer;
206       processor.SetActor( actor );
207     }
208   }
209
210   const Integration::PanGestureEvent& panEvent;
211   PanGestureProcessor& processor;
212 };
213
214 PanGestureProcessor::PanGestureProcessor( Stage& stage, Integration::GestureManager& gestureManager )
215 : mStage( stage ),
216   mGestureManager( gestureManager ),
217   mGestureDetectors(),
218   mCurrentPanEmitters(),
219   mCurrentRenderTask(),
220   mPossiblePanPosition(),
221   mMinTouchesRequired( 1 ),
222   mMaxTouchesRequired( 1 ),
223   mSceneObject( SceneGraph::PanGesture::New() ) // Create scene object to store pan information.
224 {
225   // Pass ownership to scene-graph
226   AddGestureMessage( mStage.GetUpdateManager(), mSceneObject );
227 }
228
229 PanGestureProcessor::~PanGestureProcessor()
230 {
231   if( Stage::IsInstalled() && ( mSceneObject != NULL ) )
232   {
233     RemoveGestureMessage( mStage.GetUpdateManager(), mSceneObject );
234     mSceneObject = NULL; // mSceneObject is about to be destroyed
235   }
236 }
237
238 void PanGestureProcessor::Process( const Integration::PanGestureEvent& panEvent )
239 {
240   switch( panEvent.state )
241   {
242     case Gesture::Possible:
243     {
244       mCurrentPanEmitters.clear();
245       ResetActor();
246
247       HitTestAlgorithm::Results hitTestResults;
248       if( HitTest( mStage, panEvent.currentPosition, hitTestResults ) )
249       {
250         SetActor( hitTestResults.actor );
251         mPossiblePanPosition = panEvent.currentPosition;
252       }
253
254       break;
255     }
256
257     case Gesture::Started:
258     {
259       if ( GetCurrentGesturedActor() )
260       {
261         // The pan gesture should only be sent to the gesture detector which first received it so that
262         // it can be told when the gesture ends as well.
263
264         HitTestAlgorithm::Results hitTestResults;
265         HitTestAlgorithm::HitTest( mStage, mPossiblePanPosition, hitTestResults ); // Hit test original possible position...
266
267         if ( hitTestResults.actor && ( GetCurrentGesturedActor() == &GetImplementation( hitTestResults.actor ) ) )
268         {
269           // Record the current render-task for Screen->Actor coordinate conversions
270           mCurrentRenderTask = hitTestResults.renderTask;
271
272           PanEventFunctor functor( panEvent, *this );
273           GestureDetectorContainer gestureDetectors;
274           UpCastContainer<PanGestureDetector>( mGestureDetectors, gestureDetectors );
275           ProcessAndEmit( hitTestResults, gestureDetectors, functor );
276         }
277         else
278         {
279           ResetActor();
280           mCurrentPanEmitters.clear();
281         }
282       }
283       break;
284     }
285
286     case Gesture::Continuing:
287     case Gesture::Finished:
288     case Gesture::Cancelled:
289     {
290       // Only send subsequent pan gesture signals if we processed the pan gesture when it started.
291       // Check if actor is still touchable.
292
293       Actor* currentGesturedActor = GetCurrentGesturedActor();
294       if ( currentGesturedActor )
295       {
296         if ( currentGesturedActor->IsHittable() && !mCurrentPanEmitters.empty() && mCurrentRenderTask )
297         {
298           PanGestureDetectorContainer outsideTouchesRangeEmitters;
299
300           // Removes emitters that no longer have the actor attached
301           // Also remove emitters whose touches are outside the range of the current pan event and add them to outsideTouchesRangeEmitters
302           PanGestureDetectorContainer::iterator endIter = std::remove_if( mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(),
303                                                                           IsNotAttachedAndOutsideTouchesRangeFunctor(currentGesturedActor, panEvent.numberOfTouches, outsideTouchesRangeEmitters) );
304           mCurrentPanEmitters.erase( endIter, mCurrentPanEmitters.end() );
305
306           Vector2 actorCoords;
307
308           if ( !outsideTouchesRangeEmitters.empty() || !mCurrentPanEmitters.empty() )
309           {
310             currentGesturedActor->ScreenToLocal( GetImplementation( mCurrentRenderTask ), actorCoords.x, actorCoords.y, panEvent.currentPosition.x, panEvent.currentPosition.y );
311
312             // EmitPanSignal checks whether we have a valid actor and whether the container we are passing in has emitters before it emits the pan.
313             EmitPanSignal(Dali::Actor(currentGesturedActor), outsideTouchesRangeEmitters, panEvent, actorCoords, Gesture::Finished, mCurrentRenderTask);
314             EmitPanSignal(Dali::Actor(currentGesturedActor), mCurrentPanEmitters, panEvent, actorCoords, panEvent.state, mCurrentRenderTask);
315           }
316
317           if ( mCurrentPanEmitters.empty() )
318           {
319             // If we have no emitters attached then clear pan actor as well.
320             ResetActor();
321           }
322
323           // Clear current gesture detectors if pan gesture has ended or been cancelled.
324           if ( ( panEvent.state == Gesture::Finished ) || ( panEvent.state == Gesture::Cancelled ) )
325           {
326             mCurrentPanEmitters.clear();
327             ResetActor();
328           }
329         }
330         else
331         {
332           mCurrentPanEmitters.clear();
333           ResetActor();
334         }
335       }
336       break;
337     }
338
339     case Gesture::Clear:
340       DALI_ASSERT_ALWAYS( false && "Incorrect state received from Integration layer: Clear\n" );
341       break;
342   }
343 }
344
345 void PanGestureProcessor::AddGestureDetector( PanGestureDetector* gestureDetector )
346 {
347   bool firstRegistration(mGestureDetectors.empty());
348
349   mGestureDetectors.push_back(gestureDetector);
350
351   // Set the pan scene object on the gesture detector
352   gestureDetector->SetSceneObject( mSceneObject );
353
354   if (firstRegistration)
355   {
356     mMinTouchesRequired = gestureDetector->GetMinimumTouchesRequired();
357     mMaxTouchesRequired = gestureDetector->GetMaximumTouchesRequired();
358
359     Integration::PanGestureRequest request;
360     request.minTouches = mMinTouchesRequired;
361     request.maxTouches = mMaxTouchesRequired;
362     mGestureManager.Register(request);
363   }
364   else
365   {
366     UpdateDetection();
367   }
368 }
369
370 void PanGestureProcessor::RemoveGestureDetector( PanGestureDetector* gestureDetector )
371 {
372   if (!mCurrentPanEmitters.empty())
373   {
374     // Check if the removed detector was one that is currently being panned and remove it from emitters.
375     PanGestureDetectorContainer::iterator endIter = std::remove( mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(), gestureDetector );
376     mCurrentPanEmitters.erase( endIter, mCurrentPanEmitters.end() );
377
378     // If we no longer have any emitters, then we should clear mCurrentGesturedActor as well
379     if ( mCurrentPanEmitters.empty() )
380     {
381       ResetActor();
382     }
383   }
384
385   // Find the detector...
386   PanGestureDetectorContainer::iterator endIter = std::remove( mGestureDetectors.begin(), mGestureDetectors.end(), gestureDetector );
387   DALI_ASSERT_DEBUG( endIter != mGestureDetectors.end() );
388
389   // ...and remove it
390   mGestureDetectors.erase(endIter, mGestureDetectors.end());
391
392   if (mGestureDetectors.empty())
393   {
394     Integration::GestureRequest request(Gesture::Pan);
395     mGestureManager.Unregister(request);
396   }
397   else
398   {
399     UpdateDetection();
400   }
401 }
402
403 void PanGestureProcessor::GestureDetectorUpdated( PanGestureDetector* gestureDetector )
404 {
405   DALI_ASSERT_DEBUG(find(mGestureDetectors.begin(), mGestureDetectors.end(), gestureDetector) != mGestureDetectors.end());
406
407   UpdateDetection();
408 }
409
410 void PanGestureProcessor::SetPanGestureProperties( const PanGesture& pan )
411 {
412   // If we are currently processing a pan gesture then just ignore
413   if ( mCurrentPanEmitters.empty() && mSceneObject )
414   {
415     // We update the scene object directly rather than sending a message.
416     // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
417     mSceneObject->AddGesture( pan );
418   }
419 }
420
421 void PanGestureProcessor::EnableProfiling()
422 {
423   mSceneObject->EnableProfiling();
424 }
425
426 void PanGestureProcessor::SetPredictionMode(int mode)
427 {
428   if( (mode < 0)
429       || (mode >= SceneGraph::PanGesture::NUM_PREDICTION_MODES) )
430   {
431     mode = SceneGraph::PanGesture::DEFAULT_PREDICTION_MODE;
432   }
433   SceneGraph::PanGesture::PredictionMode modeEnum = static_cast<SceneGraph::PanGesture::PredictionMode>(mode);
434   mSceneObject->SetPredictionMode(modeEnum);
435 }
436
437 void PanGestureProcessor::SetPredictionAmount(float amount)
438 {
439   mSceneObject->SetPredictionAmount(amount);
440 }
441
442 void PanGestureProcessor::UpdateDetection()
443 {
444   DALI_ASSERT_DEBUG(!mGestureDetectors.empty());
445
446   unsigned int minimumRequired = UINT_MAX;
447   unsigned int maximumRequired = 0;
448
449   for ( PanGestureDetectorContainer::iterator iter = mGestureDetectors.begin(), endIter = mGestureDetectors.end(); iter != endIter; ++iter )
450   {
451     PanGestureDetector* detector(*iter);
452
453     unsigned int minimum = detector->GetMinimumTouchesRequired();
454     if (minimum < minimumRequired)
455     {
456       minimumRequired = minimum;
457     }
458
459     unsigned int maximum = detector->GetMaximumTouchesRequired();
460     if (maximum > maximumRequired)
461     {
462       maximumRequired = maximum;
463     }
464   }
465
466   if ( (minimumRequired != mMinTouchesRequired)||(maximumRequired != mMaxTouchesRequired) )
467   {
468     mMinTouchesRequired = minimumRequired;
469     mMaxTouchesRequired = maximumRequired;
470
471     Integration::PanGestureRequest request;
472     request.minTouches = mMinTouchesRequired;
473     request.maxTouches = mMaxTouchesRequired;
474     mGestureManager.Update(request);
475   }
476 }
477
478 void PanGestureProcessor::EmitPanSignal( Dali::Actor actorHandle,
479                                          PanGestureDetectorContainer& gestureDetectors,
480                                          const Integration::PanGestureEvent& panEvent,
481                                          Vector2 localCurrent,
482                                          Gesture::State state,
483                                          Dali::RenderTask renderTask )
484 {
485   if ( actorHandle && !gestureDetectors.empty() )
486   {
487     Actor& actor = GetImplementation(actorHandle);
488
489     PanGesture pan(state);
490     pan.time = panEvent.time;
491
492     pan.numberOfTouches = panEvent.numberOfTouches;
493     pan.screenPosition = panEvent.currentPosition;
494     pan.position = localCurrent;
495
496     RenderTask& renderTaskImpl( GetImplementation( renderTask ) );
497
498     Vector2 localPrevious;
499     actor.ScreenToLocal( renderTaskImpl, localPrevious.x, localPrevious.y, panEvent.previousPosition.x, panEvent.previousPosition.y );
500
501     pan.displacement = localCurrent - localPrevious;
502     Vector2 previousPos( panEvent.previousPosition );
503     if ( state == Gesture::Started )
504     {
505       previousPos = mPossiblePanPosition;
506     }
507
508     pan.screenDisplacement = panEvent.currentPosition - previousPos;
509
510     pan.velocity.x = pan.displacement.x / panEvent.timeDelta;
511     pan.velocity.y = pan.displacement.y / panEvent.timeDelta;
512
513     pan.screenVelocity.x = pan.screenDisplacement.x / panEvent.timeDelta;
514     pan.screenVelocity.y = pan.screenDisplacement.y / panEvent.timeDelta;
515
516     // When the gesture ends, we may incorrectly get a ZERO velocity (as we have lifted our finger without any movement)
517     // so we should use the last recorded velocity instead in this scenario.
518     if ( ( state == Gesture::Finished ) && ( pan.screenVelocity == Vector2::ZERO ) &&
519          ( panEvent.timeDelta < MAXIMUM_TIME_WITH_VALID_LAST_VELOCITY ) )
520     {
521       pan.velocity = mLastVelocity;
522       pan.screenVelocity = mLastScreenVelocity;
523     }
524     else
525     {
526       // Store the current velocity for future iterations.
527       mLastVelocity = pan.velocity;
528       mLastScreenVelocity = pan.screenVelocity;
529     }
530
531     if ( mSceneObject )
532     {
533       // We update the scene object directly rather than sending a message.
534       // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
535       mSceneObject->AddGesture( pan );
536     }
537
538     for ( PanGestureDetectorContainer::iterator iter = gestureDetectors.begin(), endIter = gestureDetectors.end(); iter != endIter; ++iter )
539     {
540       (*iter)->EmitPanGestureSignal(actorHandle, pan);
541     }
542   }
543 }
544
545 void PanGestureProcessor::OnGesturedActorStageDisconnection()
546 {
547   mCurrentPanEmitters.clear();
548 }
549
550 } // namespace Internal
551
552 } // namespace Dali