Revert "[Tizen] Not execute the remove callback"
[platform/core/uifw/dali-core.git] / dali / internal / event / events / hit-test-algorithm-impl.cpp
1 /*
2  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/event/events/hit-test-algorithm-impl.h>
20
21 // INTERNAL INCLUDES
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>
35
36 namespace Dali
37 {
38 namespace Internal
39 {
40 namespace HitTestAlgorithm
41 {
42 namespace
43 {
44 struct HitActor
45 {
46   HitActor()
47   : actor(nullptr),
48     distance(std::numeric_limits<float>::max()),
49     depth(std::numeric_limits<int>::min())
50   {
51   }
52
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.
57 };
58
59 /**
60  * Creates an Actor handle so that a HitTestFunction provided via the public API can be called.
61  */
62 struct HitTestFunctionWrapper : public HitTestInterface
63 {
64   /**
65    * Constructor
66    *
67    * @param[in] func HitTestFunction to call with an Actor handle.
68    */
69   HitTestFunctionWrapper(Dali::HitTestAlgorithm::HitTestFunction func)
70   : mFunc(func)
71   {
72   }
73
74   bool IsActorHittable(Actor* actor) override
75   {
76     return mFunc(Dali::Actor(actor), Dali::HitTestAlgorithm::CHECK_ACTOR);
77   }
78
79   bool DescendActorHierarchy(Actor* actor) override
80   {
81     return mFunc(Dali::Actor(actor), Dali::HitTestAlgorithm::DESCEND_ACTOR_TREE);
82   }
83
84   bool DoesLayerConsumeHit(Layer* layer) override
85   {
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
89     return false;
90   }
91
92   bool ActorRequiresHitResultCheck(Actor* actor, Integration::Point point, Vector2 hitPointLocal, uint32_t timeStamp) override
93   {
94     return actor->EmitHitTestResultSignal(point, hitPointLocal, timeStamp);
95   }
96
97   Dali::HitTestAlgorithm::HitTestFunction mFunc;
98 };
99
100 /**
101  * Used in the hit-test algorithm to check whether the actor is touchable.
102  * It is used by the touch event processor.
103  */
104 struct ActorTouchableCheck : public HitTestInterface
105 {
106   bool IsActorHittable(Actor* actor) override
107   {
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?
110   }
111
112   bool DescendActorHierarchy(Actor* actor) override
113   {
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.
116   }
117
118   bool DoesLayerConsumeHit(Layer* layer) override
119   {
120     return layer->IsTouchConsumed();
121   }
122
123   bool ActorRequiresHitResultCheck(Actor* actor, Integration::Point point, Vector2 hitPointLocal, uint32_t timeStamp) override
124   {
125     if(point.GetState() != PointState::STARTED && actor->IsAllowedOnlyOwnTouch() && ownActor != actor)
126     {
127       return false;
128     }
129     return actor->EmitHitTestResultSignal(point, hitPointLocal, timeStamp);
130   }
131
132   void SetOwnActor(const Actor* actor)
133   {
134     ownActor = actor;
135   }
136   const Actor* ownActor;
137 };
138
139 /**
140  * Check to see if the actor we're about to hit test is exclusively owned by another rendertask?
141  */
142 bool IsActorExclusiveToAnotherRenderTask(const Actor&                               actor,
143                                          const RenderTask&                          renderTask,
144                                          const RenderTaskList::ExclusivesContainer& exclusives)
145
146 {
147   if(exclusives.size())
148   {
149     for(const auto& exclusive : exclusives)
150     {
151       if((exclusive.renderTaskPtr != &renderTask) && (exclusive.actor.GetActor() == &actor))
152       {
153         return true;
154       }
155     }
156   }
157   return false;
158 }
159
160 /**
161  * Recursively hit test all the actors, without crossing into other layers.
162  * This algorithm performs a Depth-First-Search (DFS) on all Actors within Layer.
163  * Hit-Testing each Actor, noting the distance from the Ray-Origin (3D origin
164  * of touch vector). The closest Hit-Tested Actor is that which is returned.
165  * Exceptions to this rule are:
166  * - When comparing against renderable parents, if Actor is the same distance
167  * or closer than it's renderable parent, then it takes priority.
168  */
169 HitActor HitTestWithinLayer(Actor&                                     actor,
170                             const RenderTask&                          renderTask,
171                             const RenderTaskList::ExclusivesContainer& exclusives,
172                             const Vector4&                             rayOrigin,
173                             const Vector4&                             rayDir,
174                             const float&                               nearClippingPlane,
175                             const float&                               farClippingPlane,
176                             HitTestInterface&                          hitCheck,
177                             const bool&                                overlayed,
178                             bool&                                      overlayHit,
179                             bool                                       layerIs3d,
180                             const RayTest&                             rayTest,
181                             const Integration::Point&                  point,
182                             const uint32_t                             eventTime)
183 {
184   HitActor hit;
185
186   if(IsActorExclusiveToAnotherRenderTask(actor, renderTask, exclusives))
187   {
188     return hit;
189   }
190
191   // For clipping, regardless of whether we have hit this actor or not.
192   // This is used later to ensure all nested clipped children have hit
193   // all clipping actors also for them to be counted as hit.
194   bool clippingActor  = actor.GetClippingMode() != ClippingMode::DISABLED;
195   bool overlayedActor = overlayed || actor.IsOverlay();
196
197   // If we are a clipping actor or hittable...
198   if(clippingActor || hitCheck.IsActorHittable(&actor))
199   {
200     Vector3 size(actor.GetCurrentSize());
201
202     // Ensure the actor has a valid size.
203     // If so, perform a quick ray sphere test to see if our ray is close to the actor.
204     if(size.x > 0.0f && size.y > 0.0f && rayTest.SphereTest(actor, rayOrigin, rayDir))
205     {
206       Vector2 hitPointLocal;
207       float   distance;
208
209       // Finally, perform a more accurate ray test to see if our ray actually hits the actor.
210       if(rayTest.ActorTest(actor, rayOrigin, rayDir, hitPointLocal, distance))
211       {
212         // Calculate z coordinate value in Camera Space.
213         const Matrix&  viewMatrix          = renderTask.GetCameraActor()->GetViewMatrix();
214         const Vector4& hitDir              = Vector4(rayDir.x * distance, rayDir.y * distance, rayDir.z * distance, 0.0f);
215         const float    cameraDepthDistance = (viewMatrix * hitDir).z;
216
217         // Check if cameraDepthDistance is between clipping plane
218         if(cameraDepthDistance >= nearClippingPlane && cameraDepthDistance <= farClippingPlane)
219         {
220           if(overlayHit && !overlayedActor)
221           {
222             // If we have already hit an overlay and current actor is not an overlay ignore current actor.
223           }
224           else
225           {
226             if(overlayedActor)
227             {
228               overlayHit = true;
229             }
230
231             // If the hit actor does not want to hit, the hit-test continues.
232             if(hitCheck.ActorRequiresHitResultCheck(&actor, point, hitPointLocal, eventTime))
233             {
234               hit.actor       = &actor;
235               hit.hitPosition = hitPointLocal;
236               hit.distance    = distance;
237               hit.depth       = actor.GetSortingDepth();
238
239               if(actor.GetRendererCount() > 0)
240               {
241                 //Get renderer with maximum depth
242                 int rendererMaxDepth(actor.GetRendererAt(0).Get()->GetDepthIndex());
243                 for(uint32_t i(1); i < actor.GetRendererCount(); ++i)
244                 {
245                   int depth = actor.GetRendererAt(i).Get()->GetDepthIndex();
246                   if(depth > rendererMaxDepth)
247                   {
248                     rendererMaxDepth = depth;
249                   }
250                 }
251                 hit.depth += rendererMaxDepth;
252               }
253             }
254           }
255         }
256       }
257     }
258   }
259
260   // If current actor is clipping, and hit failed, We should not checkup child actors. Fast return
261   if(clippingActor && !(hit.actor))
262   {
263     return hit;
264   }
265
266   // Find a child hit, until we run out of actors in the current layer.
267   HitActor childHit;
268   if(actor.GetChildCount() > 0)
269   {
270     childHit.distance        = std::numeric_limits<float>::max();
271     childHit.depth           = std::numeric_limits<int32_t>::min();
272     ActorContainer& children = actor.GetChildrenInternal();
273
274     // Hit test ALL children and calculate their distance.
275     bool parentIsRenderable = actor.IsRenderable();
276
277     for(ActorIter iter = children.begin(), endIter = children.end(); iter != endIter; ++iter)
278     {
279       // Descend tree only if...
280       if(!(*iter)->IsLayer() &&                           // Child is NOT a layer, hit testing current layer only
281          (hitCheck.DescendActorHierarchy((*iter).Get()))) // We can descend into child hierarchy
282       {
283         HitActor currentHit(HitTestWithinLayer((*iter->Get()),
284                                                renderTask,
285                                                exclusives,
286                                                rayOrigin,
287                                                rayDir,
288                                                nearClippingPlane,
289                                                farClippingPlane,
290                                                hitCheck,
291                                                overlayedActor,
292                                                overlayHit,
293                                                layerIs3d,
294                                                rayTest,
295                                                point,
296                                                eventTime));
297
298         // Make sure the set hit actor is actually hittable. This is usually required when we have some
299         // clipping as we need to hit-test all actors as we descend the tree regardless of whether they
300         // are hittable or not.
301         if(currentHit.actor && (!hitCheck.IsActorHittable(currentHit.actor)))
302         {
303           continue;
304         }
305
306         bool updateChildHit = false;
307         if(currentHit.distance >= 0.0f)
308         {
309           if(layerIs3d)
310           {
311             updateChildHit = ((currentHit.depth > childHit.depth) ||
312                               ((currentHit.depth == childHit.depth) && (currentHit.distance < childHit.distance)));
313           }
314           else
315           {
316             updateChildHit = currentHit.depth >= childHit.depth;
317           }
318         }
319
320         if(updateChildHit)
321         {
322           if(!parentIsRenderable || currentHit.depth > hit.depth ||
323              (layerIs3d && (currentHit.depth == hit.depth && currentHit.distance < hit.distance)))
324           {
325             childHit = currentHit;
326           }
327         }
328       }
329     }
330   }
331
332   return (childHit.actor) ? childHit : hit;
333 }
334
335 /**
336  * Return true if actor is sourceActor or a descendent of sourceActor
337  */
338 bool IsWithinSourceActors(const Actor& sourceActor, const Actor& actor)
339 {
340   if(&sourceActor == &actor)
341   {
342     return true;
343   }
344
345   Actor* parent = actor.GetParent();
346   if(parent)
347   {
348     return IsWithinSourceActors(sourceActor, *parent);
349   }
350
351   // Not within source actors
352   return false;
353 }
354
355 /**
356  * Returns true if the layer and all of the layer's parents are visible and sensitive.
357  */
358 inline bool IsActuallyHittable(Layer& layer, const Vector2& screenCoordinates, const Vector2& stageSize, HitTestInterface& hitCheck)
359 {
360   bool hittable(true);
361
362   if(layer.IsClipping())
363   {
364     ClippingBox box = layer.GetClippingBox();
365
366     if(screenCoordinates.x < static_cast<float>(box.x) ||
367        screenCoordinates.x > static_cast<float>(box.x + box.width) ||
368        screenCoordinates.y < stageSize.y - static_cast<float>(box.y + box.height) ||
369        screenCoordinates.y > stageSize.y - static_cast<float>(box.y))
370     {
371       // Not touchable if clipping is enabled in the layer and the screen coordinate is outside the clip region.
372       hittable = false;
373     }
374   }
375
376   if(hittable)
377   {
378     Actor* actor(&layer);
379
380     // Ensure that we can descend into the layer's (or any of its parent's) hierarchy.
381     while(actor && hittable)
382     {
383       if(!hitCheck.DescendActorHierarchy(actor))
384       {
385         hittable = false;
386         break;
387       }
388       actor = actor->GetParent();
389     }
390   }
391
392   return hittable;
393 }
394
395 /**
396  * Gets the near and far clipping planes of the camera from which the scene is viewed in the render task.
397  */
398 void GetCameraClippingPlane(RenderTask& renderTask, float& nearClippingPlane, float& farClippingPlane)
399 {
400   CameraActor* cameraActor = renderTask.GetCameraActor();
401   nearClippingPlane        = cameraActor->GetNearClippingPlane();
402   farClippingPlane         = cameraActor->GetFarClippingPlane();
403 }
404
405 /**
406  * Hit test a RenderTask
407  */
408 bool HitTestRenderTask(const RenderTaskList::ExclusivesContainer& exclusives,
409                        const Vector2&                             sceneSize,
410                        LayerList&                                 layers,
411                        RenderTask&                                renderTask,
412                        Vector2                                    screenCoordinates,
413                        Results&                                   results,
414                        HitTestInterface&                          hitCheck,
415                        const RayTest&                             rayTest)
416 {
417   if(renderTask.IsHittable(screenCoordinates))
418   {
419     Viewport viewport;
420     renderTask.GetViewport(viewport);
421     if(screenCoordinates.x < static_cast<float>(viewport.x) ||
422        screenCoordinates.x > static_cast<float>(viewport.x + viewport.width) ||
423        screenCoordinates.y < static_cast<float>(viewport.y) ||
424        screenCoordinates.y > static_cast<float>(viewport.y + viewport.height))
425     {
426       // The screen coordinate is outside the viewport of render task. The viewport clips all layers.
427       return false;
428     }
429
430     float nearClippingPlane, farClippingPlane;
431     GetCameraClippingPlane(renderTask, nearClippingPlane, farClippingPlane);
432
433     // Determine the layer depth of the source actor
434     Actor* sourceActor(renderTask.GetSourceActor());
435     if(sourceActor)
436     {
437       Dali::Layer layer(sourceActor->GetLayer());
438       if(layer)
439       {
440         const uint32_t sourceActorDepth(layer.GetProperty<bool>(Dali::Layer::Property::DEPTH));
441
442         CameraActor* cameraActor     = renderTask.GetCameraActor();
443         bool         pickingPossible = cameraActor->BuildPickingRay(
444           screenCoordinates,
445           viewport,
446           results.rayOrigin,
447           results.rayDirection);
448         if(!pickingPossible)
449         {
450           return false;
451         }
452
453         // Hit test starting with the top layer, working towards the bottom layer.
454         HitActor hit;
455         bool     overlayHit       = false;
456         bool     layerConsumesHit = false;
457
458         for(int32_t i = layers.GetLayerCount() - 1; i >= 0 && !(hit.actor); --i)
459         {
460           Layer* layer(layers.GetLayer(i));
461           overlayHit = false;
462
463           // Ensure layer is touchable (also checks whether ancestors are also touchable)
464           if(IsActuallyHittable(*layer, screenCoordinates, sceneSize, hitCheck))
465           {
466             // Always hit-test the source actor; otherwise test whether the layer is below the source actor in the hierarchy
467             if(sourceActorDepth == static_cast<uint32_t>(i))
468             {
469               // Recursively hit test the source actor & children, without crossing into other layers.
470               hit = HitTestWithinLayer(*sourceActor,
471                                        renderTask,
472                                        exclusives,
473                                        results.rayOrigin,
474                                        results.rayDirection,
475                                        nearClippingPlane,
476                                        farClippingPlane,
477                                        hitCheck,
478                                        overlayHit,
479                                        overlayHit,
480                                        layer->GetBehavior() == Dali::Layer::LAYER_3D,
481                                        rayTest,
482                                        results.point,
483                                        results.eventTime);
484             }
485             else if(IsWithinSourceActors(*sourceActor, *layer))
486             {
487               // Recursively hit test all the actors, without crossing into other layers.
488               hit = HitTestWithinLayer(*layer,
489                                        renderTask,
490                                        exclusives,
491                                        results.rayOrigin,
492                                        results.rayDirection,
493                                        nearClippingPlane,
494                                        farClippingPlane,
495                                        hitCheck,
496                                        overlayHit,
497                                        overlayHit,
498                                        layer->GetBehavior() == Dali::Layer::LAYER_3D,
499                                        rayTest,
500                                        results.point,
501                                        results.eventTime);
502             }
503
504             // If this layer is set to consume the hit, then do not check any layers behind it
505             if(hitCheck.DoesLayerConsumeHit(layer))
506             {
507               layerConsumesHit = true;
508               break;
509             }
510           }
511         }
512
513         if(hit.actor)
514         {
515           results.renderTask       = RenderTaskPtr(&renderTask);
516           results.actor            = Dali::Actor(hit.actor);
517           results.actorCoordinates = hit.hitPosition;
518
519           return true; // Success
520         }
521
522         if(layerConsumesHit)
523         {
524           return true; // Also success if layer is consuming the hit
525         }
526       }
527     }
528   }
529   return false;
530 }
531
532 /**
533  * Iterate through the RenderTaskList and perform hit testing.
534  *
535  * @param[in] sceneSize The scene size the tests will be performed in
536  * @param[in] layers The list of layers to test
537  * @param[in] taskList The list of render tasks
538  * @param[out] results Ray information calculated by the camera
539  * @param[in] hitCheck The hit testing interface object to use
540  * @param[in] onScreen True to test on-screen, false to test off-screen
541  * @return True if we have a hit, false otherwise
542  */
543 bool HitTestRenderTaskList(const Vector2&    sceneSize,
544                            LayerList&        layers,
545                            RenderTaskList&   taskList,
546                            const Vector2&    screenCoordinates,
547                            Results&          results,
548                            HitTestInterface& hitCheck,
549                            bool              onScreen)
550 {
551   RenderTaskList::RenderTaskContainer&                  tasks      = taskList.GetTasks();
552   RenderTaskList::RenderTaskContainer::reverse_iterator endIter    = tasks.rend();
553   const auto&                                           exclusives = taskList.GetExclusivesList();
554   RayTest                                               rayTest;
555
556   for(RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter)
557   {
558     RenderTask& renderTask            = *iter->Get();
559     const bool  isOffscreenRenderTask = renderTask.GetFrameBuffer();
560     if((onScreen && isOffscreenRenderTask) || (!onScreen && !isOffscreenRenderTask))
561     {
562       // Skip to next task
563       continue;
564     }
565     if(HitTestRenderTask(exclusives, sceneSize, layers, renderTask, screenCoordinates, results, hitCheck, rayTest))
566     {
567       // Return true when an actor is hit (or layer in our render-task consumes the hit)
568       return true; // don't bother checking off screen tasks
569     }
570   }
571
572   return false;
573 }
574
575 /**
576  * Iterate through the RenderTaskList and perform hit testing for both on-screen and off-screen.
577  *
578  * @param[in] sceneSize The scene size the tests will be performed in
579  * @param[in] layers The list of layers to test
580  * @param[in] taskList The list of render tasks
581  * @param[out] results Ray information calculated by the camera
582  * @param[in] hitCheck The hit testing interface object to use
583  * @param[in] onScreen True to test on-screen, false to test off-screen
584  * @return True if we have a hit, false otherwise
585  */
586 bool HitTestForEachRenderTask(const Vector2&    sceneSize,
587                               LayerList&        layers,
588                               RenderTaskList&   taskList,
589                               const Vector2&    screenCoordinates,
590                               Results&          results,
591                               HitTestInterface& hitCheck)
592 {
593   bool result = false;
594
595   // Check on-screen tasks before off-screen ones.
596   // Hit test order should be reverse of draw order (see ProcessRenderTasks() where off-screen tasks are drawn first).
597   if(HitTestRenderTaskList(sceneSize, layers, taskList, screenCoordinates, results, hitCheck, true) ||
598      HitTestRenderTaskList(sceneSize, layers, taskList, screenCoordinates, results, hitCheck, false))
599   {
600     // Found hit.
601     result = true;
602   }
603
604   return result;
605 }
606
607 } // unnamed namespace
608
609 HitTestInterface::~HitTestInterface() = default;
610
611 bool HitTest(const Vector2& sceneSize, RenderTaskList& taskList, LayerList& layerList, const Vector2& screenCoordinates, Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func)
612 {
613   bool wasHit(false);
614   // Hit-test the regular on-scene actors
615   Results                hitTestResults;
616   HitTestFunctionWrapper hitTestFunctionWrapper(func);
617   if(HitTestForEachRenderTask(sceneSize, layerList, taskList, screenCoordinates, hitTestResults, hitTestFunctionWrapper))
618   {
619     results.actor            = hitTestResults.actor;
620     results.actorCoordinates = hitTestResults.actorCoordinates;
621     wasHit                   = true;
622   }
623   return wasHit;
624 }
625
626 bool HitTest(const Vector2& sceneSize, RenderTaskList& renderTaskList, LayerList& layerList, const Vector2& screenCoordinates, Results& results, HitTestInterface& hitTestInterface)
627 {
628   bool wasHit(false);
629
630   // Hit-test the regular on-scene actors
631   if(!wasHit)
632   {
633     wasHit = HitTestForEachRenderTask(sceneSize, layerList, renderTaskList, screenCoordinates, results, hitTestInterface);
634   }
635   return wasHit;
636 }
637
638 bool HitTest(const Vector2& sceneSize, RenderTaskList& renderTaskList, LayerList& layerList, const Vector2& screenCoordinates, Results& results, const Actor* ownActor)
639 {
640   ActorTouchableCheck actorTouchableCheck;
641   actorTouchableCheck.SetOwnActor(ownActor);
642   return HitTest(sceneSize, renderTaskList, layerList, screenCoordinates, results, actorTouchableCheck);
643 }
644
645 } // namespace HitTestAlgorithm
646
647 } // namespace Internal
648
649 } // namespace Dali