2 * Copyright (c) 2022 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/debug.h>
23 #include <dali/internal/event/actors/actor-impl.h>
24 #include <dali/internal/event/actors/camera-actor-impl.h>
25 #include <dali/internal/event/actors/layer-impl.h>
26 #include <dali/internal/event/actors/layer-list.h>
27 #include <dali/internal/event/common/projection.h>
28 #include <dali/internal/event/events/ray-test.h>
29 #include <dali/internal/event/render-tasks/render-task-impl.h>
30 #include <dali/internal/event/render-tasks/render-task-list-impl.h>
31 #include <dali/internal/event/rendering/renderer-impl.h>
32 #include <dali/public-api/actors/layer.h>
33 #include <dali/public-api/math/vector2.h>
34 #include <dali/public-api/math/vector4.h>
40 namespace HitTestAlgorithm
48 distance(std::numeric_limits<float>::max()),
49 depth(std::numeric_limits<int>::min())
53 Actor* actor; ///< The actor hit (if actor is hit, then this is initialised).
54 Vector2 hitPosition; ///< Position of hit (only valid if actor valid).
55 float distance; ///< Distance from ray origin to hit actor.
56 int32_t depth; ///< Depth index of this actor.
60 * Creates an Actor handle so that a HitTestFunction provided via the public API can be called.
62 struct HitTestFunctionWrapper : public HitTestInterface
67 * @param[in] func HitTestFunction to call with an Actor handle.
69 HitTestFunctionWrapper(Dali::HitTestAlgorithm::HitTestFunction func)
74 bool IsActorHittable(Actor* actor) override
76 return mFunc(Dali::Actor(actor), Dali::HitTestAlgorithm::CHECK_ACTOR);
79 bool DescendActorHierarchy(Actor* actor) override
81 return mFunc(Dali::Actor(actor), Dali::HitTestAlgorithm::DESCEND_ACTOR_TREE);
84 bool DoesLayerConsumeHit(Layer* layer) override
86 // Layer::IsTouchConsumed() focuses on touch only. Here we are a wrapper for the public-api
87 // where the caller may want to check for something completely different.
88 // TODO: Should provide a means to let caller decide. For now do not allow layers to consume
92 bool ActorRequiresHitResultCheck(Actor* actor, Integration::Point point, Vector2 hitPointLocal, uint32_t timeStamp) override
94 return actor->EmitHitTestResultSignal(point, hitPointLocal, timeStamp);
97 Dali::HitTestAlgorithm::HitTestFunction mFunc;
101 * Used in the hit-test algorithm to check whether the actor is touchable.
102 * It is used by the touch event processor.
104 struct ActorTouchableCheck : public HitTestInterface
106 bool IsActorHittable(Actor* actor) override
108 return (actor->GetTouchRequired() || actor->GetInterceptTouchRequired() || actor->IsTouchFocusable()) && // Does the Application or derived actor type require a touch event or a intercept touch event? or focusable by touch?
109 actor->IsHittable(); // Is actor sensitive, visible and on the scene?
112 bool DescendActorHierarchy(Actor* actor) override
114 return actor->IsVisible() && // Actor is visible, if not visible then none of its children are visible.
115 actor->IsSensitive(); // Actor is sensitive, if insensitive none of its children should be hittable either.
118 bool DoesLayerConsumeHit(Layer* layer) override
120 return layer->IsTouchConsumed();
123 bool ActorRequiresHitResultCheck(Actor* actor, Integration::Point point, Vector2 hitPointLocal, uint32_t timeStamp) override
125 return actor->EmitHitTestResultSignal(point, hitPointLocal, timeStamp);
130 * Check to see if the actor we're about to hit test is exclusively owned by another rendertask?
132 bool IsActorExclusiveToAnotherRenderTask(const Actor& actor,
133 const RenderTask& renderTask,
134 const RenderTaskList::ExclusivesContainer& exclusives)
137 if(exclusives.size())
139 for(const auto& exclusive : exclusives)
141 if((exclusive.renderTaskPtr != &renderTask) && (exclusive.actor.GetActor() == &actor))
151 * Recursively hit test all the actors, without crossing into other layers.
152 * This algorithm performs a Depth-First-Search (DFS) on all Actors within Layer.
153 * Hit-Testing each Actor, noting the distance from the Ray-Origin (3D origin
154 * of touch vector). The closest Hit-Tested Actor is that which is returned.
155 * Exceptions to this rule are:
156 * - When comparing against renderable parents, if Actor is the same distance
157 * or closer than it's renderable parent, then it takes priority.
159 HitActor HitTestWithinLayer(Actor& actor,
160 const RenderTask& renderTask,
161 const RenderTaskList::ExclusivesContainer& exclusives,
162 const Vector4& rayOrigin,
163 const Vector4& rayDir,
164 float& nearClippingPlane,
165 float& farClippingPlane,
166 HitTestInterface& hitCheck,
169 uint32_t clippingDepth,
170 uint32_t clippingBitPlaneMask,
171 const RayTest& rayTest,
172 const Integration::Point& point,
173 const uint32_t eventTime)
177 if(IsActorExclusiveToAnotherRenderTask(actor, renderTask, exclusives))
182 // For clipping, regardless of whether we have hit this actor or not,
183 // we increase the clipping depth if we have hit a clipping actor.
184 // This is used later to ensure all nested clipped children have hit
185 // all clipping actors also for them to be counted as hit.
186 uint32_t newClippingDepth = clippingDepth;
187 bool clippingActor = actor.GetClippingMode() != ClippingMode::DISABLED;
193 // If we are a clipping actor or hittable...
194 if(clippingActor || hitCheck.IsActorHittable(&actor))
196 Vector3 size(actor.GetCurrentSize());
198 // Ensure the actor has a valid size.
199 // If so, perform a quick ray sphere test to see if our ray is close to the actor.
200 if(size.x > 0.0f && size.y > 0.0f && rayTest.SphereTest(actor, rayOrigin, rayDir))
202 Vector2 hitPointLocal;
205 // Finally, perform a more accurate ray test to see if our ray actually hits the actor.
206 if(rayTest.ActorTest(actor, rayOrigin, rayDir, hitPointLocal, distance))
208 // Calculate z coordinate value in Camera Space.
209 const Matrix& viewMatrix = renderTask.GetCameraActor()->GetViewMatrix();
210 const Vector4& hitDir = Vector4(rayDir.x * distance, rayDir.y * distance, rayDir.z * distance, 0.0f);
211 const float cameraDepthDistance = (viewMatrix * hitDir).z;
213 // Check if cameraDepthDistance is between clipping plane
214 if(cameraDepthDistance >= nearClippingPlane && cameraDepthDistance <= farClippingPlane)
216 // If the hit has happened on a clipping actor, then add this clipping depth to the mask of hit clipping depths.
217 // This mask shows all the actors that have been hit at different clipping depths.
220 clippingBitPlaneMask |= 1u << clippingDepth;
223 if(overlayHit && !actor.IsOverlay())
225 // If we have already hit an overlay and current actor is not an overlay ignore current actor.
229 if(actor.IsOverlay())
234 // At this point we have hit an actor.
235 // Now perform checks for clipping.
236 // Assume we have hit the actor first as if it is not clipped this would be the case.
237 bool haveHitActor = true;
239 // Check if we are performing clipping. IE. if any actors so far have clipping enabled - not necessarily this one.
240 // We can do this by checking the clipping depth has a value 1 or above.
241 if(newClippingDepth >= 1u)
243 // Now for us to count this actor as hit, we must have also hit
244 // all CLIPPING actors up to this point in the hierarchy as well.
245 // This information is stored in the clippingBitPlaneMask we updated above.
246 // Here we calculate a comparison mask by setting all the bits up to the current depth value.
247 // EG. a depth of 4 (10000 binary) = a mask of 1111 binary.
248 // This allows us a fast way of comparing all bits are set up to this depth.
249 // Note: If the current Actor has clipping, that is included in the depth mask too.
250 uint32_t clippingDepthMask = (1u << newClippingDepth) - 1u;
252 // The two masks must be equal to be a hit, as we are already assuming a hit
253 // (for non-clipping mode) then they must be not-equal to disqualify the hit.
254 if(clippingBitPlaneMask != clippingDepthMask)
256 haveHitActor = false;
260 // If the hit actor does not want to hit, the hit-test continues.
261 if(haveHitActor && hitCheck.ActorRequiresHitResultCheck(&actor, point, hitPointLocal, eventTime))
264 hit.hitPosition = hitPointLocal;
265 hit.distance = distance;
266 hit.depth = actor.GetSortingDepth();
268 if(actor.GetRendererCount() > 0)
270 //Get renderer with maximum depth
271 int rendererMaxDepth(actor.GetRendererAt(0).Get()->GetDepthIndex());
272 for(uint32_t i(1); i < actor.GetRendererCount(); ++i)
274 int depth = actor.GetRendererAt(i).Get()->GetDepthIndex();
275 if(depth > rendererMaxDepth)
277 rendererMaxDepth = depth;
280 hit.depth += rendererMaxDepth;
289 // Find a child hit, until we run out of actors in the current layer.
291 if(actor.GetChildCount() > 0)
293 childHit.distance = std::numeric_limits<float>::max();
294 childHit.depth = std::numeric_limits<int32_t>::min();
295 ActorContainer& children = actor.GetChildrenInternal();
297 // Hit test ALL children and calculate their distance.
298 bool parentIsRenderable = actor.IsRenderable();
300 for(ActorIter iter = children.begin(), endIter = children.end(); iter != endIter; ++iter)
302 // Descend tree only if...
303 if(!(*iter)->IsLayer() && // Child is NOT a layer, hit testing current layer only
304 (hitCheck.DescendActorHierarchy((*iter).Get()))) // We can descend into child hierarchy
306 HitActor currentHit(HitTestWithinLayer((*iter->Get()),
317 clippingBitPlaneMask,
322 // Make sure the set hit actor is actually hittable. This is usually required when we have some
323 // clipping as we need to hit-test all actors as we descend the tree regardless of whether they
324 // are hittable or not.
325 if(currentHit.actor && (!hitCheck.IsActorHittable(currentHit.actor)))
330 bool updateChildHit = false;
331 if(currentHit.distance >= 0.0f)
335 updateChildHit = ((currentHit.depth > childHit.depth) ||
336 ((currentHit.depth == childHit.depth) && (currentHit.distance < childHit.distance)));
340 updateChildHit = currentHit.depth >= childHit.depth;
346 if(!parentIsRenderable || currentHit.depth > hit.depth ||
347 (layerIs3d && (currentHit.depth == hit.depth && currentHit.distance < hit.distance)))
349 childHit = currentHit;
356 return (childHit.actor) ? childHit : hit;
360 * Return true if actor is sourceActor or a descendent of sourceActor
362 bool IsWithinSourceActors(const Actor& sourceActor, const Actor& actor)
364 if(&sourceActor == &actor)
369 Actor* parent = actor.GetParent();
372 return IsWithinSourceActors(sourceActor, *parent);
375 // Not within source actors
380 * Returns true if the layer and all of the layer's parents are visible and sensitive.
382 inline bool IsActuallyHittable(Layer& layer, const Vector2& screenCoordinates, const Vector2& stageSize, HitTestInterface& hitCheck)
386 if(layer.IsClipping())
388 ClippingBox box = layer.GetClippingBox();
390 if(screenCoordinates.x < static_cast<float>(box.x) ||
391 screenCoordinates.x > static_cast<float>(box.x + box.width) ||
392 screenCoordinates.y < stageSize.y - static_cast<float>(box.y + box.height) ||
393 screenCoordinates.y > stageSize.y - static_cast<float>(box.y))
395 // Not touchable if clipping is enabled in the layer and the screen coordinate is outside the clip region.
402 Actor* actor(&layer);
404 // Ensure that we can descend into the layer's (or any of its parent's) hierarchy.
405 while(actor && hittable)
407 if(!hitCheck.DescendActorHierarchy(actor))
412 actor = actor->GetParent();
420 * Gets the near and far clipping planes of the camera from which the scene is viewed in the render task.
422 void GetCameraClippingPlane(RenderTask& renderTask, float& nearClippingPlane, float& farClippingPlane)
424 CameraActor* cameraActor = renderTask.GetCameraActor();
425 nearClippingPlane = cameraActor->GetNearClippingPlane();
426 farClippingPlane = cameraActor->GetFarClippingPlane();
430 * Hit test a RenderTask
432 bool HitTestRenderTask(const RenderTaskList::ExclusivesContainer& exclusives,
433 const Vector2& sceneSize,
435 RenderTask& renderTask,
436 Vector2 screenCoordinates,
438 HitTestInterface& hitCheck,
439 const RayTest& rayTest)
441 if(renderTask.IsHittable(screenCoordinates))
444 renderTask.GetViewport(viewport);
445 if(screenCoordinates.x < static_cast<float>(viewport.x) ||
446 screenCoordinates.x > static_cast<float>(viewport.x + viewport.width) ||
447 screenCoordinates.y < static_cast<float>(viewport.y) ||
448 screenCoordinates.y > static_cast<float>(viewport.y + viewport.height))
450 // The screen coordinate is outside the viewport of render task. The viewport clips all layers.
454 float nearClippingPlane, farClippingPlane;
455 GetCameraClippingPlane(renderTask, nearClippingPlane, farClippingPlane);
457 // Determine the layer depth of the source actor
458 Actor* sourceActor(renderTask.GetSourceActor());
461 Dali::Layer layer(sourceActor->GetLayer());
464 const uint32_t sourceActorDepth(layer.GetProperty<bool>(Dali::Layer::Property::DEPTH));
466 CameraActor* cameraActor = renderTask.GetCameraActor();
467 bool pickingPossible = cameraActor->BuildPickingRay(
471 results.rayDirection);
477 // Hit test starting with the top layer, working towards the bottom layer.
479 bool overlayHit = false;
480 bool layerConsumesHit = false;
482 for(int32_t i = layers.GetLayerCount() - 1; i >= 0 && !(hit.actor); --i)
484 Layer* layer(layers.GetLayer(i));
487 // Ensure layer is touchable (also checks whether ancestors are also touchable)
488 if(IsActuallyHittable(*layer, screenCoordinates, sceneSize, hitCheck))
490 // Always hit-test the source actor; otherwise test whether the layer is below the source actor in the hierarchy
491 if(sourceActorDepth == static_cast<uint32_t>(i))
493 // Recursively hit test the source actor & children, without crossing into other layers.
494 hit = HitTestWithinLayer(*sourceActor,
498 results.rayDirection,
503 layer->GetBehavior() == Dali::Layer::LAYER_3D,
510 else if(IsWithinSourceActors(*sourceActor, *layer))
512 // Recursively hit test all the actors, without crossing into other layers.
513 hit = HitTestWithinLayer(*layer,
517 results.rayDirection,
522 layer->GetBehavior() == Dali::Layer::LAYER_3D,
530 // If this layer is set to consume the hit, then do not check any layers behind it
531 if(hitCheck.DoesLayerConsumeHit(layer))
533 layerConsumesHit = true;
541 results.renderTask = RenderTaskPtr(&renderTask);
542 results.actor = Dali::Actor(hit.actor);
543 results.actorCoordinates = hit.hitPosition;
545 return true; // Success
550 return true; // Also success if layer is consuming the hit
559 * Iterate through the RenderTaskList and perform hit testing.
561 * @param[in] sceneSize The scene size the tests will be performed in
562 * @param[in] layers The list of layers to test
563 * @param[in] taskList The list of render tasks
564 * @param[out] results Ray information calculated by the camera
565 * @param[in] hitCheck The hit testing interface object to use
566 * @param[in] onScreen True to test on-screen, false to test off-screen
567 * @return True if we have a hit, false otherwise
569 bool HitTestRenderTaskList(const Vector2& sceneSize,
571 RenderTaskList& taskList,
572 const Vector2& screenCoordinates,
574 HitTestInterface& hitCheck,
577 RenderTaskList::RenderTaskContainer& tasks = taskList.GetTasks();
578 RenderTaskList::RenderTaskContainer::reverse_iterator endIter = tasks.rend();
579 const auto& exclusives = taskList.GetExclusivesList();
582 for(RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter)
584 RenderTask& renderTask = *iter->Get();
585 const bool isOffscreenRenderTask = renderTask.GetFrameBuffer();
586 if((onScreen && isOffscreenRenderTask) || (!onScreen && !isOffscreenRenderTask))
591 if(HitTestRenderTask(exclusives, sceneSize, layers, renderTask, screenCoordinates, results, hitCheck, rayTest))
593 // Return true when an actor is hit (or layer in our render-task consumes the hit)
594 return true; // don't bother checking off screen tasks
602 * Iterate through the RenderTaskList and perform hit testing for both on-screen and off-screen.
604 * @param[in] sceneSize The scene size the tests will be performed in
605 * @param[in] layers The list of layers to test
606 * @param[in] taskList The list of render tasks
607 * @param[out] results Ray information calculated by the camera
608 * @param[in] hitCheck The hit testing interface object to use
609 * @param[in] onScreen True to test on-screen, false to test off-screen
610 * @return True if we have a hit, false otherwise
612 bool HitTestForEachRenderTask(const Vector2& sceneSize,
614 RenderTaskList& taskList,
615 const Vector2& screenCoordinates,
617 HitTestInterface& hitCheck)
621 // Check on-screen tasks before off-screen ones.
622 // Hit test order should be reverse of draw order (see ProcessRenderTasks() where off-screen tasks are drawn first).
623 if(HitTestRenderTaskList(sceneSize, layers, taskList, screenCoordinates, results, hitCheck, true) ||
624 HitTestRenderTaskList(sceneSize, layers, taskList, screenCoordinates, results, hitCheck, false))
633 } // unnamed namespace
635 HitTestInterface::~HitTestInterface() = default;
637 bool HitTest(const Vector2& sceneSize, RenderTaskList& taskList, LayerList& layerList, const Vector2& screenCoordinates, Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func)
640 // Hit-test the regular on-scene actors
641 Results hitTestResults;
642 HitTestFunctionWrapper hitTestFunctionWrapper(func);
643 if(HitTestForEachRenderTask(sceneSize, layerList, taskList, screenCoordinates, hitTestResults, hitTestFunctionWrapper))
645 results.actor = hitTestResults.actor;
646 results.actorCoordinates = hitTestResults.actorCoordinates;
652 bool HitTest(const Vector2& sceneSize, RenderTaskList& renderTaskList, LayerList& layerList, const Vector2& screenCoordinates, Results& results, HitTestInterface& hitTestInterface)
656 // Hit-test the regular on-scene actors
659 wasHit = HitTestForEachRenderTask(sceneSize, layerList, renderTaskList, screenCoordinates, results, hitTestInterface);
664 bool HitTest(const Vector2& sceneSize, RenderTaskList& renderTaskList, LayerList& layerList, const Vector2& screenCoordinates, Results& results)
666 ActorTouchableCheck actorTouchableCheck;
667 return HitTest(sceneSize, renderTaskList, layerList, screenCoordinates, results, actorTouchableCheck);
670 } // namespace HitTestAlgorithm
672 } // namespace Internal