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/layer-impl.h>
29 #include <dali/internal/event/actors/layer-list.h>
30 #include <dali/internal/event/actors/renderable-actor-impl.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
56 distance( std::numeric_limits<float>::max() ),
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 bool overlay; ///< true if the hit actor is an overlay
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 Dali::HitTestAlgorithm::HitTestFunction mFunc;
99 * Used in the hit-test algorithm to check whether the actor is touchable.
100 * It is used by the touch event processor.
102 struct ActorTouchableCheck : public HitTestInterface
104 virtual bool IsActorHittable( Actor* actor )
106 return actor->GetTouchRequired() && // Does the Application or derived actor type require a touch event?
107 actor->IsHittable(); // Is actor sensitive, visible and on the scene?
110 virtual bool DescendActorHierarchy( Actor* actor )
112 return actor->IsVisible() && // Actor is visible, if not visible then none of its children are visible.
113 actor->IsSensitive(); // Actor is sensitive, if insensitive none of its children should be hittable either.
118 * Recursively hit test all the actors, without crossing into other layers.
119 * This algorithm performs a Depth-First-Search (DFS) on all Actors within Layer.
120 * Hit-Testing each Actor, noting the distance from the Ray-Origin (3D origin
121 * of touch vector). The closest Hit-Tested Actor is that which is returned.
122 * Exceptions to this rule are:
123 * - If the Actor is an overlay then it is considered closer than all previous
124 * overlays encountered in the hit test traversal.
125 * - When comparing against renderable parents, if Actor is the same distance
126 * or closer than it's renderable parent, then it takes priority.
128 HitActor HitTestWithinLayer( Actor& actor,
129 const Vector4& rayOrigin,
130 const Vector4& rayDir,
132 float& nearClippingPlane,
133 float& farClippingPlane,
134 HitTestInterface& hitCheck,
135 bool& stencilOnLayer,
137 bool parentIsStencil )
139 worldOverlay |= actor.IsOverlay();
143 // Children should inherit the stencil draw mode
144 bool isStencil = parentIsStencil;
146 if ( actor.GetDrawMode() == DrawMode::STENCIL && actor.IsVisible() )
149 stencilOnLayer = true;
152 // If we are a stencil or hittable...
153 if ( isStencil || hitCheck.IsActorHittable( &actor ) )
155 Vector3 size( actor.GetCurrentSize() );
157 if ( size.x > 0.0f && size.y > 0.0f && // Ensure the actor has a valid size.
158 actor.RaySphereTest( rayOrigin, rayDir ) ) // Perform quicker ray sphere test to see if our ray is close to the actor.
160 Vector4 hitPointLocal;
163 // Finally, perform a more accurate ray test to see if our ray actually hits the actor.
164 if( actor.RayActorTest( rayOrigin, rayDir, hitPointLocal, distance ) )
166 if( distance >= nearClippingPlane && distance <= farClippingPlane )
168 // If the hit has happened on a stencil then register, but don't record as hit result
176 hit.x = hitPointLocal.x;
177 hit.y = hitPointLocal.y;
178 hit.distance = distance;
179 hit.overlay = worldOverlay;
186 // If there is a stencil on this layer and we've also registered a hit, then don't both searching any children
187 if ( stencilHit && hit.actor )
192 // Find a child hit, until we run out of actors in the current layer.
194 if( actor.GetChildCount() > 0 )
196 childHit.distance = std::numeric_limits<float>::max();
197 Dali::ActorContainer& children = actor.GetChildrenInternal();
199 // Hit test ALL children and calculate their distance.
200 bool parentIsRenderable = actor.IsRenderable();
202 for (Dali::ActorIter iter = children.begin(), endIter = children.end(); iter != endIter; ++iter)
204 // Descend tree only if...
205 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
206 ( isStencil || hitCheck.DescendActorHierarchy( &GetImplementation( *iter ) ) ) ) // We are a stencil OR we can descend into child hierarchy
208 HitActor currentHit( HitTestWithinLayer( GetImplementation(*iter), rayOrigin, rayDir, worldOverlay, nearClippingPlane, farClippingPlane, hitCheck, stencilOnLayer, stencilHit, isStencil ) );
210 // If Current child is an overlay, then it takes priority.
211 // If it is not an overlay, and the previously hit sibling is also not an overlay, then closest takes priority.
212 // (last overlay sibling has priority as is rendered on top)
213 if ( currentHit.distance >= 0.f && (currentHit.overlay || (!childHit.overlay && currentHit.distance < childHit.distance) ) )
215 if ( !parentIsRenderable )
217 // If our parent is not renderable, then child should be hit regardless of distance.
218 childHit = currentHit;
220 else if ( currentHit.overlay || (!hit.overlay && currentHit.distance <= hit.distance) )
222 // If our parent is renderable, then child should only be hit if it is an overlay, or if it is closer than a non-overlay.
223 // (child overlay has priority as is rendered on top of it's parent)
224 childHit = currentHit;
230 return ( childHit.actor ) ? childHit : hit;
234 * Return true if actor is sourceActor or a descendent of sourceActor
236 bool IsWithinSourceActors( const Actor& sourceActor, const Actor& actor )
238 if ( &sourceActor == &actor )
244 Actor* parent = actor.GetParent();
247 return IsWithinSourceActors( sourceActor, *parent );
251 // Not within source actors
256 * Returns true if the layer and all of the layer's parents are visible and sensitive.
258 inline bool IsActuallyHittable( Layer& layer, const Vector2& screenCoordinates, const Vector2& stageSize, HitTestInterface& hitCheck )
260 bool hittable( true );
262 if(layer.IsClipping())
264 ClippingBox box = layer.GetClippingBox();
266 if( screenCoordinates.x < box.x ||
267 screenCoordinates.x > box.x + box.width ||
268 screenCoordinates.y < stageSize.y - (box.y + box.height) ||
269 screenCoordinates.y > stageSize.y - box.y)
271 // Not touchable if clipping is enabled in the layer and the screen coordinate is outside the clip region.
278 Actor* actor( &layer );
280 // Ensure that we can descend into the layer's (or any of its parent's) hierarchy.
281 while ( actor && hittable )
283 if ( ! hitCheck.DescendActorHierarchy( actor ) )
288 actor = actor->GetParent();
296 * Gets the near and far clipping planes of the camera from which the scene is viewed in the render task.
298 void GetCameraClippingPlane( RenderTask& renderTask, float& nearClippingPlane, float& farClippingPlane )
300 CameraActor* cameraActor = renderTask.GetCameraActor();
301 nearClippingPlane = cameraActor->GetNearClippingPlane();
302 farClippingPlane = cameraActor->GetFarClippingPlane();
306 * Hit test a RenderTask
308 bool HitTestRenderTask( LayerList& layers,
309 RenderTask& renderTask,
310 Vector2 screenCoordinates,
312 HitTestInterface& hitCheck )
314 if ( renderTask.IsHittable( screenCoordinates ) )
317 renderTask.GetViewport( viewport );
318 if( screenCoordinates.x < viewport.x ||
319 screenCoordinates.x > viewport.x + viewport.width ||
320 screenCoordinates.y < viewport.y ||
321 screenCoordinates.y > viewport.y + viewport.height )
323 // The screen coordinate is outside the viewport of render task. The viewport clips all layers.
327 float nearClippingPlane, farClippingPlane;
328 GetCameraClippingPlane(renderTask, nearClippingPlane, farClippingPlane);
330 // Determine the layer depth of the source actor
331 Actor* sourceActor( renderTask.GetSourceActor() );
334 Dali::Layer layer( sourceActor->GetLayer() );
337 const unsigned int sourceActorDepth( layer.GetDepth() );
339 CameraActor* cameraActor = renderTask.GetCameraActor();
340 bool pickingPossible = cameraActor->BuildPickingRay(
344 results.rayDirection );
345 if( !pickingPossible )
350 // Hit test starting with the top layer, working towards the bottom layer.
352 bool stencilOnLayer = false;
353 bool stencilHit = false;
354 const Vector2& stageSize = Stage::GetCurrent()->GetSize();
356 for (int i=layers.GetLayerCount()-1; i>=0 && !(hit.actor); --i)
358 Layer* layer( layers.GetLayer(i) );
360 HitActor previousHit = hit;
361 stencilOnLayer = false;
364 // Ensure layer is touchable (also checks whether ancestors are also touchable)
365 if ( IsActuallyHittable ( *layer, screenCoordinates, stageSize, hitCheck ) )
367 // Always hit-test the source actor; otherwise test whether the layer is below the source actor in the hierarchy
368 if ( sourceActorDepth == static_cast<unsigned int>(i) )
370 // Recursively hit test the source actor & children, without crossing into other layers.
371 hit = HitTestWithinLayer( *sourceActor, results.rayOrigin, results.rayDirection, false, nearClippingPlane, farClippingPlane, hitCheck, stencilOnLayer, stencilHit, false );
373 else if ( IsWithinSourceActors( *sourceActor, *layer ) )
375 // Recursively hit test all the actors, without crossing into other layers.
376 hit = HitTestWithinLayer( *layer, results.rayOrigin, results.rayDirection, false, nearClippingPlane, farClippingPlane, hitCheck, stencilOnLayer, stencilHit, false );
378 // If a stencil on this layer hasn't been hit, then discard hit results for this layer
379 if ( stencilOnLayer && !stencilHit )
387 results.renderTask = Dali::RenderTask(&renderTask);
388 results.actor = Dali::Actor(hit.actor);
389 results.actorCoordinates.x = hit.x;
390 results.actorCoordinates.y = hit.y;
391 return true; // Success
400 * Iterate through RenderTaskList and perform hit test.
403 void HitTestForEachRenderTask( LayerList& layers,
404 RenderTaskList& taskList,
405 const Vector2& screenCoordinates,
407 HitTestInterface& hitCheck )
409 RenderTaskList::RenderTaskContainer& tasks = taskList.GetTasks();
410 RenderTaskList::RenderTaskContainer::reverse_iterator endIter = tasks.rend();
412 // Check onscreen tasks before offscreen ones, hit test order should be reverse of draw order (see ProcessRenderTasks() where offscreen tasks are drawn first).
415 for ( RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter )
417 RenderTask& renderTask = GetImplementation( *iter );
418 Dali::FrameBufferImage frameBufferImage = renderTask.GetTargetFrameBuffer();
420 // Note that if frameBufferImage is NULL we are using the default (on screen) render target
423 ResourceId id = GetImplementation(frameBufferImage).GetResourceId();
433 if ( HitTestRenderTask( layers, renderTask, screenCoordinates, results, hitCheck ) )
435 // Exit when an actor is hit
436 return; // don't bother checking off screen tasks
441 for ( RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter )
443 RenderTask& renderTask = GetImplementation( *iter );
444 Dali::FrameBufferImage frameBufferImage = renderTask.GetTargetFrameBuffer();
446 // Note that if frameBufferImage is NULL we are using the default (on screen) render target
449 ResourceId id = GetImplementation(frameBufferImage).GetResourceId();
458 if ( HitTestRenderTask( layers, renderTask, screenCoordinates, results, hitCheck ) )
460 // Exit when an actor is hit
467 } // unnamed namespace
469 void HitTest( Stage& stage, const Vector2& screenCoordinates, Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func )
471 // Hit-test the regular on-stage actors
472 RenderTaskList& taskList = stage.GetRenderTaskList();
473 LayerList& layerList = stage.GetLayerList();
475 Results hitTestResults;
476 HitTestFunctionWrapper hitTestFunctionWrapper( func );
477 HitTestForEachRenderTask( layerList, taskList, screenCoordinates, hitTestResults, hitTestFunctionWrapper );
479 results.actor = hitTestResults.actor;
480 results.actorCoordinates = hitTestResults.actorCoordinates;
483 void HitTest( Stage& stage, const Vector2& screenCoordinates, Results& results, HitTestInterface& hitTestInterface )
485 // Hit-test the system-overlay actors first
486 SystemOverlay* systemOverlay = stage.GetSystemOverlayInternal();
490 RenderTaskList& overlayTaskList = systemOverlay->GetOverlayRenderTasks();
491 LayerList& overlayLayerList = systemOverlay->GetLayerList();
493 HitTestForEachRenderTask( overlayLayerList, overlayTaskList, screenCoordinates, results, hitTestInterface );
496 // Hit-test the regular on-stage actors
497 if ( !results.actor )
499 RenderTaskList& taskList = stage.GetRenderTaskList();
500 LayerList& layerList = stage.GetLayerList();
502 HitTestForEachRenderTask( layerList, taskList, screenCoordinates, results, hitTestInterface );
506 void HitTest( Stage& stage, const Vector2& screenCoordinates, Results& results )
508 ActorTouchableCheck actorTouchableCheck;
509 HitTest( stage, screenCoordinates, results, actorTouchableCheck );
512 void HitTest( Stage& stage, RenderTask& renderTask, const Vector2& screenCoordinates,
513 Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func )
515 Results hitTestResults;
516 HitTestFunctionWrapper hitTestFunctionWrapper( func );
517 HitTestRenderTask( stage.GetLayerList(), renderTask, screenCoordinates, hitTestResults, hitTestFunctionWrapper );
518 results.actor = hitTestResults.actor;
519 results.actorCoordinates = hitTestResults.actorCoordinates;
522 } // namespace HitTestAlgorithm
524 } // namespace Internal