2 * Copyright (c) 2014 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/math/vector2.h>
24 #include <dali/public-api/math/vector4.h>
25 #include <dali/integration-api/debug.h>
26 #include <dali/internal/event/actors/actor-impl.h>
27 #include <dali/internal/event/actors/camera-actor-impl.h>
28 #include <dali/internal/event/actors/image-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/actors/renderable-actor-impl.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>
45 namespace HitTestAlgorithm
57 distance( std::numeric_limits<float>::max() ),
58 depth( std::numeric_limits<int>::min() )
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
71 * Creates an Actor handle so that a HitTestFunction provided via the public API can be called.
73 struct HitTestFunctionWrapper : public HitTestInterface
78 * @param[in] func HitTestFunction to call with an Actor handle.
80 HitTestFunctionWrapper( Dali::HitTestAlgorithm::HitTestFunction func )
85 virtual bool IsActorHittable( Actor* actor )
87 return mFunc( Dali::Actor( actor ), Dali::HitTestAlgorithm::CHECK_ACTOR );
90 virtual bool DescendActorHierarchy( Actor* actor )
92 return mFunc( Dali::Actor( actor ), Dali::HitTestAlgorithm::DESCEND_ACTOR_TREE );
95 virtual bool DoesLayerConsumeHit( Layer* layer )
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
103 Dali::HitTestAlgorithm::HitTestFunction mFunc;
107 * Used in the hit-test algorithm to check whether the actor is touchable.
108 * It is used by the touch event processor.
110 struct ActorTouchableCheck : public HitTestInterface
112 virtual bool IsActorHittable( Actor* actor )
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?
118 virtual bool DescendActorHierarchy( Actor* actor )
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.
124 virtual bool DoesLayerConsumeHit( Layer* layer )
126 return layer->IsTouchConsumed();
131 * Check to see if the actor we're about to hit test is exclusively owned by another rendertask?
133 bool IsActorExclusiveToAnotherRenderTask( const Actor& actor,
134 const RenderTask& renderTask,
135 const Vector< RenderTaskList::Exclusive >& exclusives )
138 if ( exclusives.Size() )
140 for ( Vector< RenderTaskList::Exclusive >::Iterator exclusiveIt = exclusives.Begin(); exclusives.End() != exclusiveIt; ++exclusiveIt )
142 if ( exclusiveIt->renderTaskPtr != &renderTask )
144 if ( exclusiveIt->actorPtr == &actor )
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.
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,
173 bool parentIsStencil )
177 if ( IsActorExclusiveToAnotherRenderTask( actor, renderTask, exclusives ) )
182 // Children should inherit the stencil draw mode
183 bool isStencil = parentIsStencil;
185 if ( actor.GetDrawMode() == DrawMode::STENCIL && actor.IsVisible() )
188 stencilOnLayer = true;
191 // If we are a stencil or hittable...
192 if ( isStencil || hitCheck.IsActorHittable( &actor ) )
194 Vector3 size( actor.GetCurrentSize() );
196 if ( size.x > 0.0f && size.y > 0.0f && // Ensure the actor has a valid size.
197 actor.RaySphereTest( rayOrigin, rayDir ) ) // Perform quicker ray sphere test to see if our ray is close to the actor.
199 Vector4 hitPointLocal;
202 // Finally, perform a more accurate ray test to see if our ray actually hits the actor.
203 if( actor.RayActorTest( rayOrigin, rayDir, hitPointLocal, distance ) )
205 if( distance >= nearClippingPlane && distance <= farClippingPlane )
207 // If the hit has happened on a stencil then register, but don't record as hit result
215 hit.x = hitPointLocal.x;
216 hit.y = hitPointLocal.y;
217 hit.distance = distance;
219 // Is this actor an Image Actor or contains a renderer?
220 if ( ImageActor* imageActor = dynamic_cast< ImageActor* >( &actor ) )
222 hit.depth = imageActor->GetDepthIndex();
226 if ( actor.GetRendererCount() )
228 hit.depth = actor.GetRendererAt( 0 ).GetCurrentDepthIndex();
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 )
247 // Find a child hit, until we run out of actors in the current layer.
249 if( actor.GetChildCount() > 0 )
251 childHit.distance = std::numeric_limits<float>::max();
252 childHit.depth = std::numeric_limits<int>::min();
253 ActorContainer& children = actor.GetChildrenInternal();
255 // Hit test ALL children and calculate their distance.
256 bool parentIsRenderable = actor.IsRenderable();
258 for( ActorIter iter = children.begin(), endIter = children.end(); iter != endIter; ++iter )
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( &GetImplementation( *iter ) ) ) ) // We are a stencil OR we can descend into child hierarchy
264 HitActor currentHit( HitTestWithinLayer( GetImplementation(*iter),
276 bool updateChildHit = false;
277 // If our ray casting hit, then check then if the hit actor's depth is greater that the favorite, it will be preferred
278 if ( currentHit.distance >= 0.0f )
280 if ( currentHit.depth > childHit.depth )
282 updateChildHit = true;
285 // If the hit actor's depth is equal to current favorite, then we check the distance and prefer the closer
286 else if ( currentHit.depth == childHit.depth )
288 if ( currentHit.distance < childHit.distance )
290 updateChildHit = true;
295 if ( updateChildHit )
297 if( !parentIsRenderable || currentHit.depth > hit.depth ||
298 ( currentHit.depth == hit.depth && currentHit.distance < hit.distance ) )
300 childHit = currentHit;
306 return ( childHit.actor ) ? childHit : hit;
310 * Return true if actor is sourceActor or a descendent of sourceActor
312 bool IsWithinSourceActors( const Actor& sourceActor, const Actor& actor )
314 if ( &sourceActor == &actor )
320 Actor* parent = actor.GetParent();
323 return IsWithinSourceActors( sourceActor, *parent );
327 // Not within source actors
332 * Returns true if the layer and all of the layer's parents are visible and sensitive.
334 inline bool IsActuallyHittable( Layer& layer, const Vector2& screenCoordinates, const Vector2& stageSize, HitTestInterface& hitCheck )
336 bool hittable( true );
338 if(layer.IsClipping())
340 ClippingBox box = layer.GetClippingBox();
342 if( screenCoordinates.x < box.x ||
343 screenCoordinates.x > box.x + box.width ||
344 screenCoordinates.y < stageSize.y - (box.y + box.height) ||
345 screenCoordinates.y > stageSize.y - box.y)
347 // Not touchable if clipping is enabled in the layer and the screen coordinate is outside the clip region.
354 Actor* actor( &layer );
356 // Ensure that we can descend into the layer's (or any of its parent's) hierarchy.
357 while ( actor && hittable )
359 if ( ! hitCheck.DescendActorHierarchy( actor ) )
364 actor = actor->GetParent();
372 * Gets the near and far clipping planes of the camera from which the scene is viewed in the render task.
374 void GetCameraClippingPlane( RenderTask& renderTask, float& nearClippingPlane, float& farClippingPlane )
376 CameraActor* cameraActor = renderTask.GetCameraActor();
377 nearClippingPlane = cameraActor->GetNearClippingPlane();
378 farClippingPlane = cameraActor->GetFarClippingPlane();
382 * Hit test a RenderTask
384 bool HitTestRenderTask( const Vector< RenderTaskList::Exclusive >& exclusives,
386 RenderTask& renderTask,
387 Vector2 screenCoordinates,
389 HitTestInterface& hitCheck )
391 if ( renderTask.IsHittable( screenCoordinates ) )
394 renderTask.GetViewport( viewport );
395 if( screenCoordinates.x < viewport.x ||
396 screenCoordinates.x > viewport.x + viewport.width ||
397 screenCoordinates.y < viewport.y ||
398 screenCoordinates.y > viewport.y + viewport.height )
400 // The screen coordinate is outside the viewport of render task. The viewport clips all layers.
404 float nearClippingPlane, farClippingPlane;
405 GetCameraClippingPlane(renderTask, nearClippingPlane, farClippingPlane);
407 // Determine the layer depth of the source actor
408 Actor* sourceActor( renderTask.GetSourceActor() );
411 Dali::Layer layer( sourceActor->GetLayer() );
414 const unsigned int sourceActorDepth( layer.GetDepth() );
416 CameraActor* cameraActor = renderTask.GetCameraActor();
417 bool pickingPossible = cameraActor->BuildPickingRay(
421 results.rayDirection );
422 if( !pickingPossible )
427 // Hit test starting with the top layer, working towards the bottom layer.
429 bool stencilOnLayer = false;
430 bool stencilHit = false;
431 bool layerConsumesHit = false;
432 const Vector2& stageSize = Stage::GetCurrent()->GetSize();
434 for (int i=layers.GetLayerCount()-1; i>=0 && !(hit.actor); --i)
436 Layer* layer( layers.GetLayer(i) );
437 HitActor previousHit = hit;
438 stencilOnLayer = false;
441 // Ensure layer is touchable (also checks whether ancestors are also touchable)
442 if ( IsActuallyHittable ( *layer, screenCoordinates, stageSize, hitCheck ) )
444 // Always hit-test the source actor; otherwise test whether the layer is below the source actor in the hierarchy
445 if ( sourceActorDepth == static_cast<unsigned int>(i) )
447 // Recursively hit test the source actor & children, without crossing into other layers.
448 hit = HitTestWithinLayer( *sourceActor,
452 results.rayDirection,
460 else if ( IsWithinSourceActors( *sourceActor, *layer ) )
462 // Recursively hit test all the actors, without crossing into other layers.
463 hit = HitTestWithinLayer( *layer,
467 results.rayDirection,
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() )
483 // If this layer is set to consume the hit, then do not check any layers behind it
484 if ( hitCheck.DoesLayerConsumeHit( layer ) )
486 layerConsumesHit = true;
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
499 else if ( layerConsumesHit )
501 return true; // Also success if layer is consuming the hit
510 * Iterate through RenderTaskList and perform hit test.
512 * @return true if we have a hit, false otherwise
514 bool HitTestForEachRenderTask( LayerList& layers,
515 RenderTaskList& taskList,
516 const Vector2& screenCoordinates,
518 HitTestInterface& hitCheck )
520 RenderTaskList::RenderTaskContainer& tasks = taskList.GetTasks();
521 RenderTaskList::RenderTaskContainer::reverse_iterator endIter = tasks.rend();
523 const Vector< RenderTaskList::Exclusive >& exclusives = taskList.GetExclusivesList();
525 // Check onscreen tasks before offscreen ones, hit test order should be reverse of draw order (see ProcessRenderTasks() where offscreen tasks are drawn first).
528 for ( RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter )
530 RenderTask& renderTask = GetImplementation( *iter );
531 Dali::FrameBufferImage frameBufferImage = renderTask.GetTargetFrameBuffer();
533 // Note that if frameBufferImage is NULL we are using the default (on screen) render target
536 ResourceId id = GetImplementation(frameBufferImage).GetResourceId();
546 if ( HitTestRenderTask( exclusives, layers, renderTask, screenCoordinates, results, hitCheck ) )
548 // Return true when an actor is hit (or layer in our render-task consumes the hit)
549 return true; // don't bother checking off screen tasks
554 for ( RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter )
556 RenderTask& renderTask = GetImplementation( *iter );
557 Dali::FrameBufferImage frameBufferImage = renderTask.GetTargetFrameBuffer();
559 // Note that if frameBufferImage is NULL we are using the default (on screen) render target
562 ResourceId id = GetImplementation(frameBufferImage).GetResourceId();
571 if ( HitTestRenderTask( exclusives, layers, renderTask, screenCoordinates, results, hitCheck ) )
573 // Return true when an actor is hit (or a layer in our render-task consumes the hit)
581 } // unnamed namespace
583 bool HitTest( Stage& stage, const Vector2& screenCoordinates, Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func )
585 bool wasHit( false );
586 // Hit-test the regular on-stage actors
587 RenderTaskList& taskList = stage.GetRenderTaskList();
588 LayerList& layerList = stage.GetLayerList();
590 Results hitTestResults;
591 HitTestFunctionWrapper hitTestFunctionWrapper( func );
592 if ( HitTestForEachRenderTask( layerList, taskList, screenCoordinates, hitTestResults, hitTestFunctionWrapper ) )
594 results.actor = hitTestResults.actor;
595 results.actorCoordinates = hitTestResults.actorCoordinates;
601 bool HitTest( Stage& stage, const Vector2& screenCoordinates, Results& results, HitTestInterface& hitTestInterface )
603 bool wasHit( false );
605 // Hit-test the system-overlay actors first
606 SystemOverlay* systemOverlay = stage.GetSystemOverlayInternal();
610 RenderTaskList& overlayTaskList = systemOverlay->GetOverlayRenderTasks();
611 LayerList& overlayLayerList = systemOverlay->GetLayerList();
613 wasHit = HitTestForEachRenderTask( overlayLayerList, overlayTaskList, screenCoordinates, results, hitTestInterface );
616 // Hit-test the regular on-stage actors
619 RenderTaskList& taskList = stage.GetRenderTaskList();
620 LayerList& layerList = stage.GetLayerList();
622 wasHit = HitTestForEachRenderTask( layerList, taskList, screenCoordinates, results, hitTestInterface );
627 bool HitTest( Stage& stage, const Vector2& screenCoordinates, Results& results )
629 ActorTouchableCheck actorTouchableCheck;
630 return HitTest( stage, screenCoordinates, results, actorTouchableCheck );
633 bool HitTest( Stage& stage, RenderTask& renderTask, const Vector2& screenCoordinates,
634 Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func )
636 bool wasHit( false );
637 Results hitTestResults;
639 const Vector< RenderTaskList::Exclusive >& exclusives = Stage::GetCurrent()->GetRenderTaskList().GetExclusivesList();
640 HitTestFunctionWrapper hitTestFunctionWrapper( func );
641 if ( HitTestRenderTask( exclusives, stage.GetLayerList(), renderTask, screenCoordinates, hitTestResults, hitTestFunctionWrapper ) )
643 results.actor = hitTestResults.actor;
644 results.actorCoordinates = hitTestResults.actorCoordinates;
650 } // namespace HitTestAlgorithm
652 } // namespace Internal