Merge "Removed some junk from Makefile.am" into devel/master
[platform/core/uifw/dali-core.git] / dali / internal / event / events / hit-test-algorithm-impl.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 // CLASS HEADER
19 #include <dali/internal/event/events/hit-test-algorithm-impl.h>
20
21 // INTERNAL INCLUDES
22 #include <dali/integration-api/system-overlay.h>
23 #include <dali/public-api/actors/layer.h>
24 #include <dali/public-api/math/vector2.h>
25 #include <dali/public-api/math/vector4.h>
26 #include <dali/integration-api/debug.h>
27 #include <dali/internal/event/actors/actor-impl.h>
28 #include <dali/internal/event/actors/camera-actor-impl.h>
29 #include <dali/internal/event/actors/image-actor-impl.h>
30 #include <dali/internal/event/actors/layer-impl.h>
31 #include <dali/internal/event/actors/layer-list.h>
32 #include <dali/internal/event/common/system-overlay-impl.h>
33 #include <dali/internal/event/common/stage-impl.h>
34 #include <dali/internal/event/common/projection.h>
35 #include <dali/internal/event/images/frame-buffer-image-impl.h>
36 #include <dali/internal/event/render-tasks/render-task-impl.h>
37 #include <dali/internal/event/render-tasks/render-task-list-impl.h>
38
39 namespace Dali
40 {
41
42 namespace Internal
43 {
44
45 namespace HitTestAlgorithm
46 {
47
48 namespace
49 {
50
51 struct HitActor
52 {
53   HitActor()
54   : actor( NULL ),
55     x( 0 ),
56     y( 0 ),
57     distance( std::numeric_limits<float>::max() ),
58     depth( std::numeric_limits<int>::min() )
59   {
60   }
61
62   Actor *actor;                         ///< the actor hit. (if actor hit, then initialised)
63   float x;                              ///< x position of hit (only valid if actor valid)
64   float y;                              ///< y position of hit (only valid if actor valid)
65   float distance;                       ///< distance from ray origin to hit actor
66   int depth;                            ///< depth index of this actor
67
68 };
69
70 /**
71  * Creates an Actor handle so that a HitTestFunction provided via the public API can be called.
72  */
73 struct HitTestFunctionWrapper : public HitTestInterface
74 {
75   /**
76    * Constructor
77    *
78    * @param[in] func HitTestFunction to call with an Actor handle.
79    */
80   HitTestFunctionWrapper( Dali::HitTestAlgorithm::HitTestFunction func )
81   : mFunc( func )
82   {
83   }
84
85   virtual bool IsActorHittable( Actor* actor )
86   {
87     return mFunc( Dali::Actor( actor ), Dali::HitTestAlgorithm::CHECK_ACTOR );
88   }
89
90   virtual bool DescendActorHierarchy( Actor* actor )
91   {
92     return mFunc( Dali::Actor( actor ), Dali::HitTestAlgorithm::DESCEND_ACTOR_TREE );
93   }
94
95   virtual bool DoesLayerConsumeHit( Layer* layer )
96   {
97     // Layer::IsTouchConsumed() focuses on touch only. Here we are a wrapper for the public-api
98     // where the caller may want to check for something completely different.
99     // TODO: Should provide a means to let caller decide. For now do not allow layers to consume
100     return false;
101   }
102
103   Dali::HitTestAlgorithm::HitTestFunction mFunc;
104 };
105
106 /**
107  * Used in the hit-test algorithm to check whether the actor is touchable.
108  * It is used by the touch event processor.
109  */
110 struct ActorTouchableCheck : public HitTestInterface
111 {
112   virtual bool IsActorHittable( Actor* actor )
113   {
114     return actor->GetTouchRequired() && // Does the Application or derived actor type require a touch event?
115            actor->IsHittable();         // Is actor sensitive, visible and on the scene?
116   }
117
118   virtual bool DescendActorHierarchy( Actor* actor )
119   {
120     return actor->IsVisible() && // Actor is visible, if not visible then none of its children are visible.
121            actor->IsSensitive(); // Actor is sensitive, if insensitive none of its children should be hittable either.
122   }
123
124   virtual bool DoesLayerConsumeHit( Layer* layer )
125   {
126     return layer->IsTouchConsumed();
127   }
128 };
129
130 /**
131  * Check to see if the actor we're about to hit test is exclusively owned by another rendertask?
132  */
133 bool IsActorExclusiveToAnotherRenderTask( const Actor& actor,
134                                           const RenderTask& renderTask,
135                                           const Vector< RenderTaskList::Exclusive >& exclusives )
136
137 {
138   if ( exclusives.Size() )
139   {
140     for ( Vector< RenderTaskList::Exclusive >::Iterator exclusiveIt = exclusives.Begin(); exclusives.End() != exclusiveIt; ++exclusiveIt )
141     {
142       if ( exclusiveIt->renderTaskPtr != &renderTask )
143       {
144         if ( exclusiveIt->actorPtr == &actor )
145         {
146           return true;
147         }
148       }
149     }
150   }
151   return false;
152 }
153
154 /**
155  * Recursively hit test all the actors, without crossing into other layers.
156  * This algorithm performs a Depth-First-Search (DFS) on all Actors within Layer.
157  * Hit-Testing each Actor, noting the distance from the Ray-Origin (3D origin
158  * of touch vector). The closest Hit-Tested Actor is that which is returned.
159  * Exceptions to this rule are:
160  * - When comparing against renderable parents, if Actor is the same distance
161  * or closer than it's renderable parent, then it takes priority.
162  */
163 HitActor HitTestWithinLayer( Actor& actor,
164                              const RenderTask& renderTask,
165                              const Vector< RenderTaskList::Exclusive >& exclusives,
166                              const Vector4& rayOrigin,
167                              const Vector4& rayDir,
168                              float& nearClippingPlane,
169                              float& farClippingPlane,
170                              HitTestInterface& hitCheck,
171                              bool& stencilOnLayer,
172                              bool& stencilHit,
173                              bool parentIsStencil,
174                              bool layerIs3d )
175 {
176   HitActor hit;
177
178   if ( IsActorExclusiveToAnotherRenderTask( actor, renderTask, exclusives ) )
179   {
180     return hit;
181   }
182
183   // Children should inherit the stencil draw mode
184   bool isStencil = parentIsStencil;
185
186   if ( actor.GetDrawMode() == DrawMode::STENCIL && actor.IsVisible() )
187   {
188     isStencil = true;
189     stencilOnLayer = true;
190   }
191
192   // If we are a stencil or hittable...
193   if ( isStencil || hitCheck.IsActorHittable( &actor ) )
194   {
195     Vector3 size( actor.GetCurrentSize() );
196
197     if ( size.x > 0.0f && size.y > 0.0f &&          // Ensure the actor has a valid size.
198          actor.RaySphereTest( rayOrigin, rayDir ) ) // Perform quicker ray sphere test to see if our ray is close to the actor.
199     {
200       Vector4 hitPointLocal;
201       float distance;
202
203       // Finally, perform a more accurate ray test to see if our ray actually hits the actor.
204       if( actor.RayActorTest( rayOrigin, rayDir, hitPointLocal, distance ) )
205       {
206         if( distance >= nearClippingPlane && distance <= farClippingPlane )
207         {
208           // If the hit has happened on a stencil then register, but don't record as hit result
209           if ( isStencil )
210           {
211             stencilHit = true;
212           }
213           else
214           {
215             hit.actor = &actor;
216             hit.x = hitPointLocal.x;
217             hit.y = hitPointLocal.y;
218             hit.distance = distance;
219             hit.depth = actor.GetHierarchyDepth() * Dali::Layer::TREE_DEPTH_MULTIPLIER;
220
221             if ( actor.GetRendererCount() > 0 )
222             {
223               //Get renderer with maximum depth
224               int rendererMaxDepth(actor.GetRendererAt( 0 ).Get()->GetDepthIndex());
225               for( unsigned int i(1); i<actor.GetRendererCount(); ++i)
226               {
227                 int depth = actor.GetRendererAt( i ).Get()->GetDepthIndex();
228                 if( depth > rendererMaxDepth )
229                 {
230                   rendererMaxDepth = depth;
231                 }
232               }
233               hit.depth += rendererMaxDepth;
234             }
235           }
236         }
237       }
238     }
239   }
240
241   // If we are a stencil (or a child of a stencil) and we have already ascertained that the stencil has been hit then there is no need to hit-test the children of this stencil-actor
242   if ( isStencil && stencilHit  )
243   {
244     return hit;
245   }
246
247   // Find a child hit, until we run out of actors in the current layer.
248   HitActor childHit;
249   if( actor.GetChildCount() > 0 )
250   {
251     childHit.distance = std::numeric_limits<float>::max();
252     childHit.depth = std::numeric_limits<int>::min();
253     ActorContainer& children = actor.GetChildrenInternal();
254
255     // Hit test ALL children and calculate their distance.
256     bool parentIsRenderable = actor.IsRenderable();
257
258     for( ActorIter iter = children.begin(), endIter = children.end(); iter != endIter; ++iter )
259     {
260       // Descend tree only if...
261       if ( !(*iter)->IsLayer() &&    // Child is NOT a layer, hit testing current layer only or Child is not a layer and we've inherited the stencil draw mode
262            ( isStencil || hitCheck.DescendActorHierarchy( ( *iter ).Get() ) ) ) // We are a stencil OR we can descend into child hierarchy
263       {
264         HitActor currentHit( HitTestWithinLayer(  (*iter->Get()),
265                                                   renderTask,
266                                                   exclusives,
267                                                   rayOrigin,
268                                                   rayDir,
269                                                   nearClippingPlane,
270                                                   farClippingPlane,
271                                                   hitCheck,
272                                                   stencilOnLayer,
273                                                   stencilHit,
274                                                   isStencil,
275                                                   layerIs3d) );
276
277         bool updateChildHit = false;
278         if ( currentHit.distance >= 0.0f )
279         {
280           if( layerIs3d )
281           {
282             updateChildHit = ( ( currentHit.depth > childHit.depth ) ||
283                 ( ( currentHit.depth == childHit.depth ) && ( currentHit.distance < childHit.distance ) ) );
284           }
285           else
286           {
287             updateChildHit = currentHit.depth >= childHit.depth;
288           }
289         }
290
291         if ( updateChildHit )
292         {
293           if( !parentIsRenderable || currentHit.depth > hit.depth ||
294             ( layerIs3d && ( currentHit.depth == hit.depth && currentHit.distance < hit.distance )) )
295             {
296               childHit = currentHit;
297             }
298         }
299       }
300     }
301   }
302   return ( childHit.actor ) ? childHit : hit;
303 }
304
305 /**
306  * Return true if actor is sourceActor or a descendent of sourceActor
307  */
308 bool IsWithinSourceActors( const Actor& sourceActor, const Actor& actor )
309 {
310   if ( &sourceActor == &actor )
311   {
312     return true;
313   }
314   else
315   {
316     Actor* parent = actor.GetParent();
317     if ( parent )
318     {
319       return IsWithinSourceActors( sourceActor, *parent );
320     }
321   }
322
323   // Not within source actors
324   return false;
325 }
326
327 /**
328  * Returns true if the layer and all of the layer's parents are visible and sensitive.
329  */
330 inline bool IsActuallyHittable( Layer& layer, const Vector2& screenCoordinates, const Vector2& stageSize, HitTestInterface& hitCheck )
331 {
332   bool hittable( true );
333
334   if(layer.IsClipping())
335   {
336     ClippingBox box = layer.GetClippingBox();
337
338     if( screenCoordinates.x < box.x ||
339         screenCoordinates.x > box.x + box.width ||
340         screenCoordinates.y < stageSize.y - (box.y + box.height) ||
341         screenCoordinates.y > stageSize.y - box.y)
342     {
343       // Not touchable if clipping is enabled in the layer and the screen coordinate is outside the clip region.
344       hittable = false;
345     }
346   }
347
348   if(hittable)
349   {
350     Actor* actor( &layer );
351
352     // Ensure that we can descend into the layer's (or any of its parent's) hierarchy.
353     while ( actor && hittable )
354     {
355       if ( ! hitCheck.DescendActorHierarchy( actor ) )
356       {
357         hittable = false;
358         break;
359       }
360       actor = actor->GetParent();
361     }
362   }
363
364   return hittable;
365 }
366
367 /**
368  * Gets the near and far clipping planes of the camera from which the scene is viewed in the render task.
369  */
370 void GetCameraClippingPlane( RenderTask& renderTask, float& nearClippingPlane, float& farClippingPlane )
371 {
372   CameraActor* cameraActor = renderTask.GetCameraActor();
373   nearClippingPlane = cameraActor->GetNearClippingPlane();
374   farClippingPlane = cameraActor->GetFarClippingPlane();
375 }
376
377 /**
378  * Hit test a RenderTask
379  */
380 bool HitTestRenderTask( const Vector< RenderTaskList::Exclusive >& exclusives,
381                         Stage& stage,
382                         LayerList& layers,
383                         RenderTask& renderTask,
384                         Vector2 screenCoordinates,
385                         Results& results,
386                         HitTestInterface& hitCheck )
387 {
388   if ( renderTask.IsHittable( screenCoordinates ) )
389   {
390     Viewport viewport;
391     renderTask.GetViewport( viewport );
392     if( screenCoordinates.x < viewport.x ||
393         screenCoordinates.x > viewport.x + viewport.width ||
394         screenCoordinates.y < viewport.y ||
395         screenCoordinates.y > viewport.y + viewport.height )
396     {
397       // The screen coordinate is outside the viewport of render task. The viewport clips all layers.
398       return false;
399     }
400
401     float nearClippingPlane, farClippingPlane;
402     GetCameraClippingPlane(renderTask, nearClippingPlane, farClippingPlane);
403
404     // Determine the layer depth of the source actor
405     Actor* sourceActor( renderTask.GetSourceActor() );
406     if ( sourceActor )
407     {
408       Dali::Layer layer( sourceActor->GetLayer() );
409       if ( layer )
410       {
411         const unsigned int sourceActorDepth( layer.GetDepth() );
412
413         CameraActor* cameraActor = renderTask.GetCameraActor();
414         bool pickingPossible = cameraActor->BuildPickingRay(
415             screenCoordinates,
416             viewport,
417             results.rayOrigin,
418             results.rayDirection );
419         if( !pickingPossible )
420         {
421           return false;
422         }
423
424         // Hit test starting with the top layer, working towards the bottom layer.
425         HitActor hit;
426         bool stencilOnLayer = false;
427         bool stencilHit = false;
428         bool layerConsumesHit = false;
429
430         const Vector2& stageSize = stage.GetSize();
431
432         for (int i=layers.GetLayerCount()-1; i>=0 && !(hit.actor); --i)
433         {
434           Layer* layer( layers.GetLayer(i) );
435           HitActor previousHit = hit;
436           stencilOnLayer = false;
437           stencilHit = false;
438
439           // Ensure layer is touchable (also checks whether ancestors are also touchable)
440           if ( IsActuallyHittable ( *layer, screenCoordinates, stageSize, hitCheck ) )
441           {
442             // Always hit-test the source actor; otherwise test whether the layer is below the source actor in the hierarchy
443             if ( sourceActorDepth == static_cast<unsigned int>(i) )
444             {
445               // Recursively hit test the source actor & children, without crossing into other layers.
446               hit = HitTestWithinLayer( *sourceActor,
447                                         renderTask,
448                                         exclusives,
449                                         results.rayOrigin,
450                                         results.rayDirection,
451                                         nearClippingPlane,
452                                         farClippingPlane,
453                                         hitCheck,
454                                         stencilOnLayer,
455                                         stencilHit,
456                                         false,
457                                         layer->GetBehavior() == Dali::Layer::LAYER_3D);
458             }
459             else if ( IsWithinSourceActors( *sourceActor, *layer ) )
460             {
461               // Recursively hit test all the actors, without crossing into other layers.
462               hit = HitTestWithinLayer( *layer,
463                                         renderTask,
464                                         exclusives,
465                                         results.rayOrigin,
466                                         results.rayDirection,
467                                         nearClippingPlane,
468                                         farClippingPlane,
469                                         hitCheck,
470                                         stencilOnLayer,
471                                         stencilHit,
472                                         false,
473                                         layer->GetBehavior() == Dali::Layer::LAYER_3D);
474             }
475
476             // If a stencil on this layer hasn't been hit, then discard hit results for this layer if our current hit actor is renderable
477             if ( stencilOnLayer && !stencilHit &&
478                  hit.actor && hit.actor->IsRenderable() )
479             {
480               hit = previousHit;
481             }
482
483             // If this layer is set to consume the hit, then do not check any layers behind it
484             if ( hitCheck.DoesLayerConsumeHit( layer ) )
485             {
486               layerConsumesHit = true;
487               break;
488             }
489           }
490         }
491         if ( hit.actor )
492         {
493           results.renderTask = Dali::RenderTask(&renderTask);
494           results.actor = Dali::Actor(hit.actor);
495           results.actorCoordinates.x = hit.x;
496           results.actorCoordinates.y = hit.y;
497           return true; // Success
498         }
499         else if ( layerConsumesHit )
500         {
501           return true; // Also success if layer is consuming the hit
502         }
503       }
504     }
505   }
506   return false;
507 }
508
509 /**
510  * Iterate through RenderTaskList and perform hit test.
511  *
512  * @return true if we have a hit, false otherwise
513  */
514 bool HitTestForEachRenderTask( Stage& stage,
515                                LayerList& layers,
516                                RenderTaskList& taskList,
517                                const Vector2& screenCoordinates,
518                                Results& results,
519                                HitTestInterface& hitCheck )
520 {
521   RenderTaskList::RenderTaskContainer& tasks = taskList.GetTasks();
522   RenderTaskList::RenderTaskContainer::reverse_iterator endIter = tasks.rend();
523
524   const Vector< RenderTaskList::Exclusive >& exclusives = taskList.GetExclusivesList();
525
526   // Check onscreen tasks before offscreen ones, hit test order should be reverse of draw order (see ProcessRenderTasks() where offscreen tasks are drawn first).
527
528   // on screen
529   for ( RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter )
530   {
531     RenderTask& renderTask = GetImplementation( *iter );
532     Dali::FrameBufferImage frameBufferImage = renderTask.GetTargetFrameBuffer();
533
534     // Note that if frameBufferImage is NULL we are using the default (on screen) render target
535     if(frameBufferImage)
536     {
537       ResourceId id = GetImplementation(frameBufferImage).GetResourceId();
538
539       // on screen only
540       if(0 != id)
541       {
542         // Skip to next task
543         continue;
544       }
545     }
546
547     if ( HitTestRenderTask( exclusives, stage, layers, renderTask, screenCoordinates, results, hitCheck ) )
548     {
549       // Return true when an actor is hit (or layer in our render-task consumes the hit)
550       return true; // don't bother checking off screen tasks
551     }
552   }
553
554   // off screen
555   for ( RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter )
556   {
557     RenderTask& renderTask = GetImplementation( *iter );
558     Dali::FrameBufferImage frameBufferImage = renderTask.GetTargetFrameBuffer();
559
560     // Note that if frameBufferImage is NULL we are using the default (on screen) render target
561     if(frameBufferImage)
562     {
563       ResourceId id = GetImplementation(frameBufferImage).GetResourceId();
564
565       // off screen only
566       if(0 == id)
567       {
568         // Skip to next task
569         continue;
570       }
571
572       if ( HitTestRenderTask( exclusives, stage, layers, renderTask, screenCoordinates, results, hitCheck ) )
573       {
574         // Return true when an actor is hit (or a layer in our render-task consumes the hit)
575         return true;
576       }
577     }
578   }
579   return false;
580 }
581
582 } // unnamed namespace
583
584 bool HitTest( Stage& stage, const Vector2& screenCoordinates, Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func )
585 {
586   bool wasHit( false );
587   // Hit-test the regular on-stage actors
588   RenderTaskList& taskList = stage.GetRenderTaskList();
589   LayerList& layerList = stage.GetLayerList();
590
591   Results hitTestResults;
592   HitTestFunctionWrapper hitTestFunctionWrapper( func );
593   if (  HitTestForEachRenderTask( stage, layerList, taskList, screenCoordinates, hitTestResults, hitTestFunctionWrapper ) )
594   {
595     results.actor = hitTestResults.actor;
596     results.actorCoordinates = hitTestResults.actorCoordinates;
597     wasHit = true;
598   }
599   return wasHit;
600 }
601
602 bool HitTest( Stage& stage, const Vector2& screenCoordinates, Results& results, HitTestInterface& hitTestInterface )
603 {
604   bool wasHit( false );
605
606   // Hit-test the system-overlay actors first
607   SystemOverlay* systemOverlay = stage.GetSystemOverlayInternal();
608
609   if ( systemOverlay )
610   {
611     RenderTaskList& overlayTaskList = systemOverlay->GetOverlayRenderTasks();
612     LayerList& overlayLayerList = systemOverlay->GetLayerList();
613
614     wasHit = HitTestForEachRenderTask( stage, overlayLayerList, overlayTaskList, screenCoordinates, results, hitTestInterface );
615   }
616
617   // Hit-test the regular on-stage actors
618   if ( !wasHit )
619   {
620     RenderTaskList& taskList = stage.GetRenderTaskList();
621     LayerList& layerList = stage.GetLayerList();
622
623     wasHit = HitTestForEachRenderTask( stage, layerList, taskList, screenCoordinates, results, hitTestInterface );
624   }
625   return wasHit;
626 }
627
628 bool HitTest( Stage& stage, const Vector2& screenCoordinates, Results& results )
629 {
630   ActorTouchableCheck actorTouchableCheck;
631   return HitTest( stage, screenCoordinates, results, actorTouchableCheck );
632 }
633
634 bool HitTest( Stage& stage, RenderTask& renderTask, const Vector2& screenCoordinates,
635               Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func )
636 {
637   bool wasHit( false );
638   Results hitTestResults;
639
640   const Vector< RenderTaskList::Exclusive >& exclusives = stage.GetRenderTaskList().GetExclusivesList();
641   HitTestFunctionWrapper hitTestFunctionWrapper( func );
642   if ( HitTestRenderTask( exclusives, stage, stage.GetLayerList(), renderTask, screenCoordinates, hitTestResults, hitTestFunctionWrapper ) )
643   {
644     results.actor = hitTestResults.actor;
645     results.actorCoordinates = hitTestResults.actorCoordinates;
646     wasHit = true;
647   }
648   return wasHit;
649 }
650
651 } // namespace HitTestAlgorithm
652
653 } // namespace Internal
654
655 } // namespace Dali