2 * Copyright (c) 2016 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <dali/internal/event/events/hit-test-algorithm-impl.h>
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/layer-impl.h>
30 #include <dali/internal/event/actors/layer-list.h>
31 #include <dali/internal/event/common/system-overlay-impl.h>
32 #include <dali/internal/event/common/stage-impl.h>
33 #include <dali/internal/event/common/projection.h>
34 #include <dali/internal/event/images/frame-buffer-image-impl.h>
35 #include <dali/internal/event/render-tasks/render-task-impl.h>
36 #include <dali/internal/event/render-tasks/render-task-list-impl.h>
44 namespace HitTestAlgorithm
54 distance( std::numeric_limits<float>::max() ),
55 depth( std::numeric_limits<int>::min() )
59 Actor *actor; ///< The actor hit (if actor is hit, then this is initialised).
60 Vector2 hitPosition; ///< Position of hit (only valid if actor valid).
61 float distance; ///< Distance from ray origin to hit actor.
62 int depth; ///< Depth index of this actor.
66 * Creates an Actor handle so that a HitTestFunction provided via the public API can be called.
68 struct HitTestFunctionWrapper : public HitTestInterface
73 * @param[in] func HitTestFunction to call with an Actor handle.
75 HitTestFunctionWrapper( Dali::HitTestAlgorithm::HitTestFunction func )
80 virtual bool IsActorHittable( Actor* actor )
82 return mFunc( Dali::Actor( actor ), Dali::HitTestAlgorithm::CHECK_ACTOR );
85 virtual bool DescendActorHierarchy( Actor* actor )
87 return mFunc( Dali::Actor( actor ), Dali::HitTestAlgorithm::DESCEND_ACTOR_TREE );
90 virtual bool DoesLayerConsumeHit( Layer* layer )
92 // Layer::IsTouchConsumed() focuses on touch only. Here we are a wrapper for the public-api
93 // where the caller may want to check for something completely different.
94 // TODO: Should provide a means to let caller decide. For now do not allow layers to consume
98 Dali::HitTestAlgorithm::HitTestFunction mFunc;
102 * Used in the hit-test algorithm to check whether the actor is touchable.
103 * It is used by the touch event processor.
105 struct ActorTouchableCheck : public HitTestInterface
107 virtual bool IsActorHittable( Actor* actor )
109 return actor->GetTouchRequired() && // Does the Application or derived actor type require a touch event?
110 actor->IsHittable(); // Is actor sensitive, visible and on the scene?
113 virtual bool DescendActorHierarchy( Actor* actor )
115 return actor->IsVisible() && // Actor is visible, if not visible then none of its children are visible.
116 actor->IsSensitive(); // Actor is sensitive, if insensitive none of its children should be hittable either.
119 virtual bool DoesLayerConsumeHit( Layer* layer )
121 return layer->IsTouchConsumed();
126 * Check to see if the actor we're about to hit test is exclusively owned by another rendertask?
128 bool IsActorExclusiveToAnotherRenderTask( const Actor& actor,
129 const RenderTask& renderTask,
130 const Vector< RenderTaskList::Exclusive >& exclusives )
133 if( exclusives.Size() )
135 for( Vector< RenderTaskList::Exclusive >::Iterator exclusiveIt = exclusives.Begin(); exclusives.End() != exclusiveIt; ++exclusiveIt )
137 if( ( exclusiveIt->renderTaskPtr != &renderTask ) && ( exclusiveIt->actorPtr == &actor ) )
147 * Recursively hit test all the actors, without crossing into other layers.
148 * This algorithm performs a Depth-First-Search (DFS) on all Actors within Layer.
149 * Hit-Testing each Actor, noting the distance from the Ray-Origin (3D origin
150 * of touch vector). The closest Hit-Tested Actor is that which is returned.
151 * Exceptions to this rule are:
152 * - When comparing against renderable parents, if Actor is the same distance
153 * or closer than it's renderable parent, then it takes priority.
155 HitActor HitTestWithinLayer( Actor& actor,
156 const RenderTask& renderTask,
157 const Vector< RenderTaskList::Exclusive >& exclusives,
158 const Vector4& rayOrigin,
159 const Vector4& rayDir,
160 float& nearClippingPlane,
161 float& farClippingPlane,
162 HitTestInterface& hitCheck,
165 unsigned int clippingDepth,
166 unsigned int clippingBitPlaneMask )
170 if( IsActorExclusiveToAnotherRenderTask( actor, renderTask, exclusives ) )
175 // For clipping, regardless of whether we have hit this actor or not,
176 // we increase the clipping depth if we have hit a clipping actor.
177 // This is used later to ensure all nested clipped children have hit
178 // all clipping actors also for them to be counted as hit.
179 unsigned int newClippingDepth = clippingDepth;
180 bool clippingActor = actor.GetClippingMode() != ClippingMode::DISABLED;
186 // If we are a clipping actor or hittable...
187 if( clippingActor || hitCheck.IsActorHittable( &actor ) )
189 Vector3 size( actor.GetCurrentSize() );
191 // Ensure the actor has a valid size.
192 // If so, perform a quick ray sphere test to see if our ray is close to the actor.
193 if( size.x > 0.0f && size.y > 0.0f && actor.RaySphereTest( rayOrigin, rayDir ) )
195 Vector2 hitPointLocal;
198 // Finally, perform a more accurate ray test to see if our ray actually hits the actor.
199 if( actor.RayActorTest( rayOrigin, rayDir, hitPointLocal, distance ) )
201 if( distance >= nearClippingPlane && distance <= farClippingPlane )
203 // If the hit has happened on a clipping actor, then add this clipping depth to the mask of hit clipping depths.
204 // This mask shows all the actors that have been hit at different clipping depths.
207 clippingBitPlaneMask |= 1u << clippingDepth;
210 if( overlayHit && !actor.IsOverlay() )
212 // If we have already hit an overlay and current actor is not an overlay ignore current actor.
216 if( actor.IsOverlay() )
221 // At this point we have hit an actor.
222 // Now perform checks for clipping.
223 // Assume we have hit the actor first as if it is not clipped this would be the case.
224 bool haveHitActor = true;
226 // Check if we are performing clipping. IE. if any actors so far have clipping enabled - not necessarily this one.
227 // We can do this by checking the clipping depth has a value 1 or above.
228 if( newClippingDepth >= 1u )
230 // Now for us to count this actor as hit, we must have also hit
231 // all CLIPPING actors up to this point in the hierarchy as well.
232 // This information is stored in the clippingBitPlaneMask we updated above.
233 // Here we calculate a comparison mask by setting all the bits up to the current depth value.
234 // EG. a depth of 4 (10000 binary) = a mask of 1111 binary.
235 // This allows us a fast way of comparing all bits are set up to this depth.
236 // Note: If the current Actor has clipping, that is included in the depth mask too.
237 unsigned int clippingDepthMask = ( 1u << newClippingDepth ) - 1u;
239 // The two masks must be equal to be a hit, as we are already assuming a hit
240 // (for non-clipping mode) then they must be not-equal to disqualify the hit.
241 if( clippingBitPlaneMask != clippingDepthMask )
243 haveHitActor = false;
250 hit.hitPosition = hitPointLocal;
251 hit.distance = distance;
252 hit.depth = actor.GetSortingDepth() ;
254 if( actor.GetRendererCount() > 0 )
256 //Get renderer with maximum depth
257 int rendererMaxDepth(actor.GetRendererAt( 0 ).Get()->GetDepthIndex());
258 for( unsigned int i(1); i < actor.GetRendererCount(); ++i )
260 int depth = actor.GetRendererAt( i ).Get()->GetDepthIndex();
261 if( depth > rendererMaxDepth )
263 rendererMaxDepth = depth;
266 hit.depth += rendererMaxDepth;
275 // Find a child hit, until we run out of actors in the current layer.
277 if( actor.GetChildCount() > 0 )
279 childHit.distance = std::numeric_limits<float>::max();
280 childHit.depth = std::numeric_limits<int>::min();
281 ActorContainer& children = actor.GetChildrenInternal();
283 // Hit test ALL children and calculate their distance.
284 bool parentIsRenderable = actor.IsRenderable();
286 for( ActorIter iter = children.begin(), endIter = children.end(); iter != endIter; ++iter )
288 // Descend tree only if...
289 if ( !( *iter )->IsLayer() && // Child is NOT a layer, hit testing current layer only
290 ( hitCheck.DescendActorHierarchy( ( *iter ).Get() ) ) ) // We can descend into child hierarchy
292 HitActor currentHit( HitTestWithinLayer( ( *iter->Get() ),
303 clippingBitPlaneMask ) );
305 bool updateChildHit = false;
306 if( currentHit.distance >= 0.0f )
310 updateChildHit = ( ( currentHit.depth > childHit.depth ) ||
311 ( ( currentHit.depth == childHit.depth ) && ( currentHit.distance < childHit.distance ) ) );
315 updateChildHit = currentHit.depth >= childHit.depth;
321 if( !parentIsRenderable || currentHit.depth > hit.depth ||
322 ( layerIs3d && ( currentHit.depth == hit.depth && currentHit.distance < hit.distance )) )
324 childHit = currentHit;
331 return ( childHit.actor ) ? childHit : hit;
335 * Return true if actor is sourceActor or a descendent of sourceActor
337 bool IsWithinSourceActors( const Actor& sourceActor, const Actor& actor )
339 if ( &sourceActor == &actor )
344 Actor* parent = actor.GetParent();
347 return IsWithinSourceActors( sourceActor, *parent );
350 // Not within source actors
355 * Returns true if the layer and all of the layer's parents are visible and sensitive.
357 inline bool IsActuallyHittable( Layer& layer, const Vector2& screenCoordinates, const Vector2& stageSize, HitTestInterface& hitCheck )
359 bool hittable( true );
361 if( layer.IsClipping() )
363 ClippingBox box = layer.GetClippingBox();
365 if( screenCoordinates.x < box.x ||
366 screenCoordinates.x > box.x + box.width ||
367 screenCoordinates.y < stageSize.y - (box.y + box.height) ||
368 screenCoordinates.y > stageSize.y - box.y)
370 // Not touchable if clipping is enabled in the layer and the screen coordinate is outside the clip region.
377 Actor* actor( &layer );
379 // Ensure that we can descend into the layer's (or any of its parent's) hierarchy.
380 while( actor && hittable )
382 if( ! hitCheck.DescendActorHierarchy( actor ) )
387 actor = actor->GetParent();
395 * Gets the near and far clipping planes of the camera from which the scene is viewed in the render task.
397 void GetCameraClippingPlane( RenderTask& renderTask, float& nearClippingPlane, float& farClippingPlane )
399 CameraActor* cameraActor = renderTask.GetCameraActor();
400 nearClippingPlane = cameraActor->GetNearClippingPlane();
401 farClippingPlane = cameraActor->GetFarClippingPlane();
405 * Hit test a RenderTask
407 bool HitTestRenderTask( const Vector< RenderTaskList::Exclusive >& exclusives,
410 RenderTask& renderTask,
411 Vector2 screenCoordinates,
413 HitTestInterface& hitCheck )
415 if ( renderTask.IsHittable( screenCoordinates ) )
418 renderTask.GetViewport( viewport );
419 if( screenCoordinates.x < viewport.x ||
420 screenCoordinates.x > viewport.x + viewport.width ||
421 screenCoordinates.y < viewport.y ||
422 screenCoordinates.y > viewport.y + viewport.height )
424 // The screen coordinate is outside the viewport of render task. The viewport clips all layers.
428 float nearClippingPlane, farClippingPlane;
429 GetCameraClippingPlane( renderTask, nearClippingPlane, farClippingPlane );
431 // Determine the layer depth of the source actor
432 Actor* sourceActor( renderTask.GetSourceActor() );
435 Dali::Layer layer( sourceActor->GetLayer() );
438 const unsigned int sourceActorDepth( layer.GetDepth() );
440 CameraActor* cameraActor = renderTask.GetCameraActor();
441 bool pickingPossible = cameraActor->BuildPickingRay(
445 results.rayDirection );
446 if( !pickingPossible )
451 // Hit test starting with the top layer, working towards the bottom layer.
453 bool overlayHit = false;
454 bool layerConsumesHit = false;
455 const Vector2& stageSize = stage.GetSize();
457 for( int i = layers.GetLayerCount() - 1; i >= 0 && !( hit.actor ); --i )
459 Layer* layer( layers.GetLayer( i ) );
462 // Ensure layer is touchable (also checks whether ancestors are also touchable)
463 if( IsActuallyHittable( *layer, screenCoordinates, stageSize, hitCheck ) )
465 // Always hit-test the source actor; otherwise test whether the layer is below the source actor in the hierarchy
466 if( sourceActorDepth == static_cast<unsigned int>( i ) )
468 // Recursively hit test the source actor & children, without crossing into other layers.
469 hit = HitTestWithinLayer( *sourceActor,
473 results.rayDirection,
478 layer->GetBehavior() == Dali::Layer::LAYER_3D,
482 else if( IsWithinSourceActors( *sourceActor, *layer ) )
484 // Recursively hit test all the actors, without crossing into other layers.
485 hit = HitTestWithinLayer( *layer,
489 results.rayDirection,
494 layer->GetBehavior() == Dali::Layer::LAYER_3D,
499 // If this layer is set to consume the hit, then do not check any layers behind it
500 if( hitCheck.DoesLayerConsumeHit( layer ) )
502 layerConsumesHit = true;
510 results.renderTask = Dali::RenderTask( &renderTask );
511 results.actor = Dali::Actor( hit.actor );
512 results.actorCoordinates = hit.hitPosition;
514 return true; // Success
517 if( layerConsumesHit )
519 return true; // Also success if layer is consuming the hit
528 * Iterate through the RenderTaskList and perform hit testing.
530 * @param[in] stage The stage the tests will be performed in
531 * @param[in] layers The list of layers to test
532 * @param[in] taskList The list of render tasks
533 * @param[out] results Ray information calculated by the camera
534 * @param[in] hitCheck The hit testing interface object to use
535 * @param[in] onScreen True to test on-screen, false to test off-screen
536 * @return True if we have a hit, false otherwise
538 bool HitTestRenderTaskList( Stage& stage,
540 RenderTaskList& taskList,
541 const Vector2& screenCoordinates,
543 HitTestInterface& hitCheck,
546 RenderTaskList::RenderTaskContainer& tasks = taskList.GetTasks();
547 RenderTaskList::RenderTaskContainer::reverse_iterator endIter = tasks.rend();
548 const Vector< RenderTaskList::Exclusive >& exclusives = taskList.GetExclusivesList();
550 for( RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter )
552 RenderTask& renderTask = GetImplementation( *iter );
553 bool isOffscreenRenderTask = ( iter->GetTargetFrameBuffer() || iter->GetFrameBuffer() );
554 if( (onScreen && isOffscreenRenderTask) || (!onScreen && !isOffscreenRenderTask) )
560 if( HitTestRenderTask( exclusives, stage, layers, renderTask, screenCoordinates, results, hitCheck ) )
562 // Return true when an actor is hit (or layer in our render-task consumes the hit)
563 return true; // don't bother checking off screen tasks
571 * Iterate through the RenderTaskList and perform hit testing for both on-screen and off-screen.
573 * @param[in] stage The stage the tests will be performed in
574 * @param[in] layers The list of layers to test
575 * @param[in] taskList The list of render tasks
576 * @param[out] results Ray information calculated by the camera
577 * @param[in] hitCheck The hit testing interface object to use
578 * @param[in] onScreen True to test on-screen, false to test off-screen
579 * @return True if we have a hit, false otherwise
581 bool HitTestForEachRenderTask( Stage& stage,
583 RenderTaskList& taskList,
584 const Vector2& screenCoordinates,
586 HitTestInterface& hitCheck )
590 // Check on-screen tasks before off-screen ones.
591 // Hit test order should be reverse of draw order (see ProcessRenderTasks() where off-screen tasks are drawn first).
592 if( HitTestRenderTaskList( stage, layers, taskList, screenCoordinates, results, hitCheck, true ) ||
593 HitTestRenderTaskList( stage, layers, taskList, screenCoordinates, results, hitCheck, false ) )
602 } // unnamed namespace
604 bool HitTest( Stage& stage, const Vector2& screenCoordinates, Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func )
606 bool wasHit( false );
607 // Hit-test the regular on-stage actors
608 RenderTaskList& taskList = stage.GetRenderTaskList();
609 LayerList& layerList = stage.GetLayerList();
611 Results hitTestResults;
612 HitTestFunctionWrapper hitTestFunctionWrapper( func );
613 if( HitTestForEachRenderTask( stage, layerList, taskList, screenCoordinates, hitTestResults, hitTestFunctionWrapper ) )
615 results.actor = hitTestResults.actor;
616 results.actorCoordinates = hitTestResults.actorCoordinates;
622 bool HitTest( Stage& stage, const Vector2& screenCoordinates, Results& results, HitTestInterface& hitTestInterface )
624 bool wasHit( false );
626 // Hit-test the system-overlay actors first
627 SystemOverlay* systemOverlay = stage.GetSystemOverlayInternal();
631 RenderTaskList& overlayTaskList = systemOverlay->GetOverlayRenderTasks();
632 LayerList& overlayLayerList = systemOverlay->GetLayerList();
634 wasHit = HitTestForEachRenderTask( stage, overlayLayerList, overlayTaskList, screenCoordinates, results, hitTestInterface );
637 // Hit-test the regular on-stage actors
640 RenderTaskList& taskList = stage.GetRenderTaskList();
641 LayerList& layerList = stage.GetLayerList();
643 wasHit = HitTestForEachRenderTask( stage, layerList, taskList, screenCoordinates, results, hitTestInterface );
648 bool HitTest( Stage& stage, const Vector2& screenCoordinates, Results& results )
650 ActorTouchableCheck actorTouchableCheck;
651 return HitTest( stage, screenCoordinates, results, actorTouchableCheck );
654 bool HitTest( Stage& stage, RenderTask& renderTask, const Vector2& screenCoordinates,
655 Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func )
657 bool wasHit( false );
658 Results hitTestResults;
660 const Vector< RenderTaskList::Exclusive >& exclusives = stage.GetRenderTaskList().GetExclusivesList();
661 HitTestFunctionWrapper hitTestFunctionWrapper( func );
662 if( HitTestRenderTask( exclusives, stage, stage.GetLayerList(), renderTask, screenCoordinates, hitTestResults, hitTestFunctionWrapper ) )
664 results.actor = hitTestResults.actor;
665 results.actorCoordinates = hitTestResults.actorCoordinates;
672 } // namespace HitTestAlgorithm
674 } // namespace Internal