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