2 * Copyright (c) 2020 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/public-api/actors/layer.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/layer-impl.h>
29 #include <dali/internal/event/actors/layer-list.h>
30 #include <dali/internal/event/common/projection.h>
31 #include <dali/internal/event/render-tasks/render-task-impl.h>
32 #include <dali/internal/event/render-tasks/render-task-list-impl.h>
40 namespace HitTestAlgorithm
50 distance( std::numeric_limits<float>::max() ),
51 depth( std::numeric_limits<int>::min() )
55 Actor *actor; ///< The actor hit (if actor is hit, then this is initialised).
56 Vector2 hitPosition; ///< Position of hit (only valid if actor valid).
57 float distance; ///< Distance from ray origin to hit actor.
58 int32_t depth; ///< Depth index of this actor.
62 * Creates an Actor handle so that a HitTestFunction provided via the public API can be called.
64 struct HitTestFunctionWrapper : public HitTestInterface
69 * @param[in] func HitTestFunction to call with an Actor handle.
71 HitTestFunctionWrapper( Dali::HitTestAlgorithm::HitTestFunction func )
76 virtual bool IsActorHittable( Actor* actor )
78 return mFunc( Dali::Actor( actor ), Dali::HitTestAlgorithm::CHECK_ACTOR );
81 virtual bool DescendActorHierarchy( Actor* actor )
83 return mFunc( Dali::Actor( actor ), Dali::HitTestAlgorithm::DESCEND_ACTOR_TREE );
86 virtual bool DoesLayerConsumeHit( Layer* layer )
88 // Layer::IsTouchConsumed() focuses on touch only. Here we are a wrapper for the public-api
89 // where the caller may want to check for something completely different.
90 // TODO: Should provide a means to let caller decide. For now do not allow layers to consume
94 Dali::HitTestAlgorithm::HitTestFunction mFunc;
98 * Used in the hit-test algorithm to check whether the actor is touchable.
99 * It is used by the touch event processor.
101 struct ActorTouchableCheck : public HitTestInterface
103 virtual bool IsActorHittable( Actor* actor )
105 return actor->GetTouchRequired() && // Does the Application or derived actor type require a touch event?
106 actor->IsHittable(); // Is actor sensitive, visible and on the scene?
109 virtual bool DescendActorHierarchy( Actor* actor )
111 return actor->IsVisible() && // Actor is visible, if not visible then none of its children are visible.
112 actor->IsSensitive(); // Actor is sensitive, if insensitive none of its children should be hittable either.
115 virtual bool DoesLayerConsumeHit( Layer* layer )
117 return layer->IsTouchConsumed();
122 * Check to see if the actor we're about to hit test is exclusively owned by another rendertask?
124 bool IsActorExclusiveToAnotherRenderTask( const Actor& actor,
125 const RenderTask& renderTask,
126 const RenderTaskList::ExclusivesContainer& exclusives )
129 if( exclusives.size() )
131 for( const auto& exclusive : exclusives )
133 if( ( exclusive.renderTaskPtr != &renderTask ) && ( exclusive.actor.GetActor() == &actor ) )
143 * Recursively hit test all the actors, without crossing into other layers.
144 * This algorithm performs a Depth-First-Search (DFS) on all Actors within Layer.
145 * Hit-Testing each Actor, noting the distance from the Ray-Origin (3D origin
146 * of touch vector). The closest Hit-Tested Actor is that which is returned.
147 * Exceptions to this rule are:
148 * - When comparing against renderable parents, if Actor is the same distance
149 * or closer than it's renderable parent, then it takes priority.
151 HitActor HitTestWithinLayer( Actor& actor,
152 const RenderTask& renderTask,
153 const RenderTaskList::ExclusivesContainer& exclusives,
154 const Vector4& rayOrigin,
155 const Vector4& rayDir,
156 float& nearClippingPlane,
157 float& farClippingPlane,
158 HitTestInterface& hitCheck,
161 uint32_t clippingDepth,
162 uint32_t clippingBitPlaneMask )
166 if( IsActorExclusiveToAnotherRenderTask( actor, renderTask, exclusives ) )
171 // For clipping, regardless of whether we have hit this actor or not,
172 // we increase the clipping depth if we have hit a clipping actor.
173 // This is used later to ensure all nested clipped children have hit
174 // all clipping actors also for them to be counted as hit.
175 uint32_t newClippingDepth = clippingDepth;
176 bool clippingActor = actor.GetClippingMode() != ClippingMode::DISABLED;
182 // If we are a clipping actor or hittable...
183 if( clippingActor || hitCheck.IsActorHittable( &actor ) )
185 Vector3 size( actor.GetCurrentSize() );
187 // Ensure the actor has a valid size.
188 // If so, perform a quick ray sphere test to see if our ray is close to the actor.
189 if( size.x > 0.0f && size.y > 0.0f && actor.RaySphereTest( rayOrigin, rayDir ) )
191 Vector2 hitPointLocal;
194 // Finally, perform a more accurate ray test to see if our ray actually hits the actor.
195 if( actor.RayActorTest( rayOrigin, rayDir, hitPointLocal, distance ) )
197 if( distance >= nearClippingPlane && distance <= farClippingPlane )
199 // If the hit has happened on a clipping actor, then add this clipping depth to the mask of hit clipping depths.
200 // This mask shows all the actors that have been hit at different clipping depths.
203 clippingBitPlaneMask |= 1u << clippingDepth;
206 if( overlayHit && !actor.IsOverlay() )
208 // If we have already hit an overlay and current actor is not an overlay ignore current actor.
212 if( actor.IsOverlay() )
217 // At this point we have hit an actor.
218 // Now perform checks for clipping.
219 // Assume we have hit the actor first as if it is not clipped this would be the case.
220 bool haveHitActor = true;
222 // Check if we are performing clipping. IE. if any actors so far have clipping enabled - not necessarily this one.
223 // We can do this by checking the clipping depth has a value 1 or above.
224 if( newClippingDepth >= 1u )
226 // Now for us to count this actor as hit, we must have also hit
227 // all CLIPPING actors up to this point in the hierarchy as well.
228 // This information is stored in the clippingBitPlaneMask we updated above.
229 // Here we calculate a comparison mask by setting all the bits up to the current depth value.
230 // EG. a depth of 4 (10000 binary) = a mask of 1111 binary.
231 // This allows us a fast way of comparing all bits are set up to this depth.
232 // Note: If the current Actor has clipping, that is included in the depth mask too.
233 uint32_t clippingDepthMask = ( 1u << newClippingDepth ) - 1u;
235 // The two masks must be equal to be a hit, as we are already assuming a hit
236 // (for non-clipping mode) then they must be not-equal to disqualify the hit.
237 if( clippingBitPlaneMask != clippingDepthMask )
239 haveHitActor = false;
246 hit.hitPosition = hitPointLocal;
247 hit.distance = distance;
248 hit.depth = actor.GetSortingDepth() ;
250 if( actor.GetRendererCount() > 0 )
252 //Get renderer with maximum depth
253 int rendererMaxDepth(actor.GetRendererAt( 0 ).Get()->GetDepthIndex());
254 for( uint32_t i(1); i < actor.GetRendererCount(); ++i )
256 int depth = actor.GetRendererAt( i ).Get()->GetDepthIndex();
257 if( depth > rendererMaxDepth )
259 rendererMaxDepth = depth;
262 hit.depth += rendererMaxDepth;
271 // Find a child hit, until we run out of actors in the current layer.
273 if( actor.GetChildCount() > 0 )
275 childHit.distance = std::numeric_limits<float>::max();
276 childHit.depth = std::numeric_limits<int32_t>::min();
277 ActorContainer& children = actor.GetChildrenInternal();
279 // Hit test ALL children and calculate their distance.
280 bool parentIsRenderable = actor.IsRenderable();
282 for( ActorIter iter = children.begin(), endIter = children.end(); iter != endIter; ++iter )
284 // Descend tree only if...
285 if ( !( *iter )->IsLayer() && // Child is NOT a layer, hit testing current layer only
286 ( hitCheck.DescendActorHierarchy( ( *iter ).Get() ) ) ) // We can descend into child hierarchy
288 HitActor currentHit( HitTestWithinLayer( ( *iter->Get() ),
299 clippingBitPlaneMask ) );
301 bool updateChildHit = false;
302 if( currentHit.distance >= 0.0f )
306 updateChildHit = ( ( currentHit.depth > childHit.depth ) ||
307 ( ( currentHit.depth == childHit.depth ) && ( currentHit.distance < childHit.distance ) ) );
311 updateChildHit = currentHit.depth >= childHit.depth;
317 if( !parentIsRenderable || currentHit.depth > hit.depth ||
318 ( layerIs3d && ( currentHit.depth == hit.depth && currentHit.distance < hit.distance )) )
320 childHit = currentHit;
327 return ( childHit.actor ) ? childHit : hit;
331 * Return true if actor is sourceActor or a descendent of sourceActor
333 bool IsWithinSourceActors( const Actor& sourceActor, const Actor& actor )
335 if ( &sourceActor == &actor )
340 Actor* parent = actor.GetParent();
343 return IsWithinSourceActors( sourceActor, *parent );
346 // Not within source actors
351 * Returns true if the layer and all of the layer's parents are visible and sensitive.
353 inline bool IsActuallyHittable( Layer& layer, const Vector2& screenCoordinates, const Vector2& stageSize, HitTestInterface& hitCheck )
355 bool hittable( true );
357 if( layer.IsClipping() )
359 ClippingBox box = layer.GetClippingBox();
361 if( screenCoordinates.x < static_cast<float>( box.x )||
362 screenCoordinates.x > static_cast<float>( box.x + box.width )||
363 screenCoordinates.y < stageSize.y - static_cast<float>( box.y + box.height ) ||
364 screenCoordinates.y > stageSize.y - static_cast<float>( box.y ) )
366 // Not touchable if clipping is enabled in the layer and the screen coordinate is outside the clip region.
373 Actor* actor( &layer );
375 // Ensure that we can descend into the layer's (or any of its parent's) hierarchy.
376 while( actor && hittable )
378 if( ! hitCheck.DescendActorHierarchy( actor ) )
383 actor = actor->GetParent();
391 * Gets the near and far clipping planes of the camera from which the scene is viewed in the render task.
393 void GetCameraClippingPlane( RenderTask& renderTask, float& nearClippingPlane, float& farClippingPlane )
395 CameraActor* cameraActor = renderTask.GetCameraActor();
396 nearClippingPlane = cameraActor->GetNearClippingPlane();
397 farClippingPlane = cameraActor->GetFarClippingPlane();
401 * Hit test a RenderTask
403 bool HitTestRenderTask( const RenderTaskList::ExclusivesContainer& exclusives,
404 const Vector2& sceneSize,
406 RenderTask& renderTask,
407 Vector2 screenCoordinates,
409 HitTestInterface& hitCheck )
411 if ( renderTask.IsHittable( screenCoordinates ) )
414 renderTask.GetViewport( viewport );
415 if( screenCoordinates.x < static_cast<float>( viewport.x ) ||
416 screenCoordinates.x > static_cast<float>( viewport.x + viewport.width ) ||
417 screenCoordinates.y < static_cast<float>( viewport.y ) ||
418 screenCoordinates.y > static_cast<float>( viewport.y + viewport.height ) )
420 // The screen coordinate is outside the viewport of render task. The viewport clips all layers.
424 float nearClippingPlane, farClippingPlane;
425 GetCameraClippingPlane( renderTask, nearClippingPlane, farClippingPlane );
427 // Determine the layer depth of the source actor
428 Actor* sourceActor( renderTask.GetSourceActor() );
431 Dali::Layer layer( sourceActor->GetLayer() );
434 const uint32_t sourceActorDepth( layer.GetProperty< bool >( Dali::Layer::Property::DEPTH ) );
436 CameraActor* cameraActor = renderTask.GetCameraActor();
437 bool pickingPossible = cameraActor->BuildPickingRay(
441 results.rayDirection );
442 if( !pickingPossible )
447 // Hit test starting with the top layer, working towards the bottom layer.
449 bool overlayHit = false;
450 bool layerConsumesHit = false;
452 for( int32_t i = layers.GetLayerCount() - 1; i >= 0 && !( hit.actor ); --i )
454 Layer* layer( layers.GetLayer( i ) );
457 // Ensure layer is touchable (also checks whether ancestors are also touchable)
458 if( IsActuallyHittable( *layer, screenCoordinates, sceneSize, hitCheck ) )
460 // Always hit-test the source actor; otherwise test whether the layer is below the source actor in the hierarchy
461 if( sourceActorDepth == static_cast<uint32_t>( i ) )
463 // Recursively hit test the source actor & children, without crossing into other layers.
464 hit = HitTestWithinLayer( *sourceActor,
468 results.rayDirection,
473 layer->GetBehavior() == Dali::Layer::LAYER_3D,
477 else if( IsWithinSourceActors( *sourceActor, *layer ) )
479 // Recursively hit test all the actors, without crossing into other layers.
480 hit = HitTestWithinLayer( *layer,
484 results.rayDirection,
489 layer->GetBehavior() == Dali::Layer::LAYER_3D,
494 // If this layer is set to consume the hit, then do not check any layers behind it
495 if( hitCheck.DoesLayerConsumeHit( layer ) )
497 layerConsumesHit = true;
505 results.renderTask = RenderTaskPtr( &renderTask );
506 results.actor = Dali::Actor( hit.actor );
507 results.actorCoordinates = hit.hitPosition;
509 return true; // Success
512 if( layerConsumesHit )
514 return true; // Also success if layer is consuming the hit
523 * Iterate through the RenderTaskList and perform hit testing.
525 * @param[in] sceneSize The scene size the tests will be performed in
526 * @param[in] layers The list of layers to test
527 * @param[in] taskList The list of render tasks
528 * @param[out] results Ray information calculated by the camera
529 * @param[in] hitCheck The hit testing interface object to use
530 * @param[in] onScreen True to test on-screen, false to test off-screen
531 * @return True if we have a hit, false otherwise
533 bool HitTestRenderTaskList( const Vector2& sceneSize,
535 RenderTaskList& taskList,
536 const Vector2& screenCoordinates,
538 HitTestInterface& hitCheck,
541 RenderTaskList::RenderTaskContainer& tasks = taskList.GetTasks();
542 RenderTaskList::RenderTaskContainer::reverse_iterator endIter = tasks.rend();
543 const auto& exclusives = taskList.GetExclusivesList();
545 for( RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter )
547 RenderTask& renderTask = *iter->Get();
548 const bool isOffscreenRenderTask = renderTask.GetFrameBuffer();
549 if( (onScreen && isOffscreenRenderTask) || (!onScreen && !isOffscreenRenderTask) )
555 if( HitTestRenderTask( exclusives, sceneSize, layers, renderTask, screenCoordinates, results, hitCheck ) )
557 // Return true when an actor is hit (or layer in our render-task consumes the hit)
558 return true; // don't bother checking off screen tasks
566 * Iterate through the RenderTaskList and perform hit testing for both on-screen and off-screen.
568 * @param[in] sceneSize The scene size the tests will be performed in
569 * @param[in] layers The list of layers to test
570 * @param[in] taskList The list of render tasks
571 * @param[out] results Ray information calculated by the camera
572 * @param[in] hitCheck The hit testing interface object to use
573 * @param[in] onScreen True to test on-screen, false to test off-screen
574 * @return True if we have a hit, false otherwise
576 bool HitTestForEachRenderTask( const Vector2& sceneSize,
578 RenderTaskList& taskList,
579 const Vector2& screenCoordinates,
581 HitTestInterface& hitCheck )
585 // Check on-screen tasks before off-screen ones.
586 // Hit test order should be reverse of draw order (see ProcessRenderTasks() where off-screen tasks are drawn first).
587 if( HitTestRenderTaskList( sceneSize, layers, taskList, screenCoordinates, results, hitCheck, true ) ||
588 HitTestRenderTaskList( sceneSize, layers, taskList, screenCoordinates, results, hitCheck, false ) )
597 } // unnamed namespace
599 HitTestInterface::~HitTestInterface()
603 bool HitTest( const Vector2& sceneSize, RenderTaskList& taskList, LayerList& layerList, const Vector2& screenCoordinates, Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func )
605 bool wasHit( false );
606 // Hit-test the regular on-scene actors
607 Results hitTestResults;
608 HitTestFunctionWrapper hitTestFunctionWrapper( func );
609 if( HitTestForEachRenderTask( sceneSize, layerList, taskList, screenCoordinates, hitTestResults, hitTestFunctionWrapper ) )
611 results.actor = hitTestResults.actor;
612 results.actorCoordinates = hitTestResults.actorCoordinates;
618 bool HitTest( const Vector2& sceneSize, RenderTaskList& renderTaskList, LayerList& layerList, const Vector2& screenCoordinates, Results& results, HitTestInterface& hitTestInterface )
620 bool wasHit( false );
622 // Hit-test the regular on-scene actors
625 wasHit = HitTestForEachRenderTask( sceneSize, layerList, renderTaskList, screenCoordinates, results, hitTestInterface );
630 bool HitTest( const Vector2& sceneSize, RenderTaskList& renderTaskList, LayerList& layerList, const Vector2& screenCoordinates, Results& results )
632 ActorTouchableCheck actorTouchableCheck;
633 return HitTest( sceneSize, renderTaskList, layerList, screenCoordinates, results, actorTouchableCheck );
636 } // namespace HitTestAlgorithm
638 } // namespace Internal