Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-30 10:40:43

0001 // SPDX-FileCopyrightText: 2020 CERN
0002 // SPDX-License-Identifier: Apache-2.0
0003 
0004 /**
0005  * @file BVHNavigator.h
0006  * @brief Navigation methods for geometry.
0007  */
0008 
0009 #ifndef BVH_NAVIGATOR_H
0010 #define BVH_NAVIGATOR_H
0011 
0012 #include "VecGeom/base/Global.h"
0013 #include "VecGeom/base/Math.h"
0014 #include "VecGeom/base/Vector3D.h"
0015 #include "VecGeom/navigation/NavigationState.h"
0016 #include "VecGeom/volumes/LogicalVolume.h"
0017 #include "VecGeom/management/BVHManager.h"
0018 #include "VecGeom/management/GeoManager.h"
0019 
0020 #ifdef VECGEOM_ENABLE_CUDA
0021 #include "VecGeom/backend/cuda/Interface.h"
0022 #endif
0023 
0024 #include <type_traits>
0025 
0026 namespace vgbrep {
0027 namespace protonav {
0028 template <typename Real_t>
0029 class BVHSurfNavigator;
0030 }
0031 } // namespace vgbrep
0032 
0033 namespace vecgeom {
0034 
0035 inline namespace VECGEOM_IMPL_NAMESPACE {
0036 class BVHSafetyEstimator;
0037 }
0038 
0039 /**
0040  * @brief IndexedBVH-accelerated navigation for placed-volume hierarchies.
0041  *
0042  * Application code uses the point-location and tracking interfaces documented
0043  * below. In particular, AdePT uses `ComputeSafety()`,
0044  * `ComputeStepAndNextVolume()`, and `RelocateToNextVolume()`. The component and
0045  * diagnostic interfaces are intended for VecGeom navigation implementations
0046  * and tests, not for transport applications.
0047  */
0048 class BVHNavigator {
0049 
0050 public:
0051   /** @name Application navigation interface
0052    *  Transport clients use these methods; BVH lookup and traversal remain internal.
0053    *  @{ */
0054 
0055   /// Boundary displacement used before or after navigation across a surface.
0056   static constexpr Precision kBoundaryPush = 10 * vecgeom::kTolerance;
0057 
0058   /**
0059    * @brief Locate the deepest daughter containing a point.
0060    * @param vol Starting placed volume.
0061    * @param point Point in the parent frame of @p vol.
0062    * @param[in,out] path State initially at the parent of @p vol; extended to the deepest containing daughter.
0063    * @param top Whether to first require that @p vol contains @p point.
0064    * @param exclude Optional volume excluded from the first daughter query.
0065    * @return Deepest containing volume, or null when the optional top check fails.
0066    */
0067   VECCORE_ATT_HOST_DEVICE
0068   static VECGEOM_FORCE_INLINE Daughter LocatePointIn(vecgeom::VPlacedVolume const *vol,
0069                                                      Vector3D<Precision> const &point, vecgeom::NavigationState &path,
0070                                                      bool top, vecgeom::VPlacedVolume const *exclude = nullptr)
0071   {
0072     return LocatePointInImpl(vol, point, path, top, exclude);
0073   }
0074 
0075   /**
0076    * @brief Relocate a local point after leaving the current top volume.
0077    * @param localpoint Point in the local frame of `path.Top()`.
0078    * @param[in,out] path State to climb and descend to the new containing volume.
0079    * @return Deepest containing volume, or null after leaving the world.
0080    */
0081   VECCORE_ATT_HOST_DEVICE
0082   static VECGEOM_FORCE_INLINE Daughter RelocatePoint(Vector3D<Precision> const &localpoint,
0083                                                      vecgeom::NavigationState &path)
0084   {
0085     return RelocatePointImpl(localpoint, path);
0086   }
0087 
0088   /**
0089    * @brief Locate the deepest daughter from the current navigation state.
0090    * @param localpoint Point in the local frame of `path.Top()`.
0091    * @param[in,out] path Starting state, extended to the deepest containing daughter.
0092    * @param top Whether to first require that the current top contains @p localpoint.
0093    * @param exclude Optional volume excluded from the first daughter query.
0094    * @return Final top volume, or null when the optional top check fails.
0095    */
0096   VECCORE_ATT_HOST_DEVICE
0097   static VECGEOM_FORCE_INLINE Daughter LocatePointInNavState(Vector3D<Precision> const &localpoint,
0098                                                              vecgeom::NavigationState &path, bool top,
0099                                                              vecgeom::VPlacedVolume const *exclude = nullptr)
0100   {
0101     return LocatePointInNavStateImpl(localpoint, path, top, exclude);
0102   }
0103 
0104   /**
0105    * @brief Compute isotropic Safety from a global point in the current state.
0106    * @param globalpoint Point in global coordinates.
0107    * @param state Current navigation state.
0108    * @param limit Accuracy limit; values above it may be conservative.
0109    * @return Safety to the nearest boundary, or infinity when @p state is outside.
0110    */
0111   VECCORE_ATT_HOST_DEVICE
0112   static VECGEOM_FORCE_INLINE Precision ComputeSafety(Vector3D<Precision> const &globalpoint,
0113                                                       vecgeom::NavigationState const &state,
0114                                                       Precision limit = InfinityLength<Precision>())
0115   {
0116     return ComputeSafetyImpl(globalpoint, state, limit);
0117   }
0118 
0119   /**
0120    * @brief Compute a bounded step and fully relocate the output state.
0121    * @param globalpoint Point in global coordinates and inside @p in_state.
0122    * @param globaldir Unit direction in global coordinates.
0123    * @param step_limit Maximum requested step.
0124    * @param in_state Current navigation state.
0125    * @param[out] out_state State at the endpoint, including transitive boundary relocation.
0126    * @return Geometry-limited or requested step length.
0127    */
0128   VECCORE_ATT_HOST_DEVICE
0129   static VECGEOM_FORCE_INLINE Precision ComputeStepAndPropagatedState(Vector3D<Precision> const &globalpoint,
0130                                                                       Vector3D<Precision> const &globaldir,
0131                                                                       Precision step_limit,
0132                                                                       vecgeom::NavigationState const &in_state,
0133                                                                       vecgeom::NavigationState &out_state)
0134   {
0135     return ComputeStepAndPropagatedStateImpl(globalpoint, globaldir, step_limit, in_state, out_state);
0136   }
0137 
0138   /**
0139    * @brief Compute a bounded step and update the state to the first crossed boundary.
0140    *
0141    * The output state enters the hit daughter or leaves the current volume, but
0142    * does not resolve additional coincident boundaries. Call
0143    * `RelocateToNextVolume()` after moving the track to the returned endpoint.
0144    *
0145    * @param globalpoint Point in global coordinates and inside @p in_state.
0146    * @param globaldir Unit direction in global coordinates.
0147    * @param step_limit Maximum requested step.
0148    * @param in_state Current navigation state.
0149    * @param[out] out_state State at the first crossed boundary, or a copy of @p in_state for a physics step.
0150    * @return Geometry-limited or requested step length.
0151    */
0152   VECCORE_ATT_HOST_DEVICE
0153   static VECGEOM_FORCE_INLINE Precision ComputeStepAndNextVolume(Vector3D<Precision> const &globalpoint,
0154                                                                  Vector3D<Precision> const &globaldir,
0155                                                                  Precision step_limit,
0156                                                                  vecgeom::NavigationState const &in_state,
0157                                                                  vecgeom::NavigationState &out_state)
0158   {
0159     return ComputeStepAndNextVolumeImpl(globalpoint, globaldir, step_limit, in_state, out_state);
0160   }
0161 
0162   /**
0163    * @brief Compute the global boundary normal pointing from current to next state.
0164    *
0165    * "Next" refers to the state transition prepared by the boundary query, not
0166    * the particle direction, which may change at the boundary. Uses the current
0167    * solid's outward normal when leaving it, or the negated daughter normal when
0168    * entering a daughter. Edges and corners follow the solid's Normal convention.
0169    *
0170    * @pre Current is inside the geometry; next is the distinct candidate boundary
0171    * path from ComputeStepAndNextVolume. Relocation has not yet been performed.
0172    * @param globalpoint Boundary endpoint in global coordinates.
0173    * @param current Original state before crossing.
0174    * @param next Candidate state from the boundary query, before relocation.
0175    * @param[out] normal Unit global normal from current toward next; unspecified on failure.
0176    * @return True if the selected solid supplies a valid normal, false otherwise.
0177    * Assemblies have no surface normal of their own.
0178    */
0179   VECCORE_ATT_HOST_DEVICE
0180   static bool ComputeNextNormal(Vector3D<Precision> const &globalpoint, vecgeom::NavigationState const &current,
0181                                 vecgeom::NavigationState const &next, Vector3D<Precision> &normal)
0182   {
0183     VECGEOM_ASSERT(!current.IsOutside() && next.IsOnBoundary());
0184     VECGEOM_ASSERT(!current.HasSamePathAsOther(next));
0185     Transformation3D transform;
0186     current.TopMatrix(transform);
0187     auto const localpoint = transform.Transform(globalpoint);
0188     bool valid;
0189     // Before relocation, a deeper next state is exactly the hit daughter.
0190     // An exit instead pops current, even when relocation will enter a sibling.
0191     if (!next.IsOutside() && next.GetLevel() > current.GetLevel()) {
0192       valid = next.Top()->Normal(localpoint, normal);
0193       if (valid) normal = -normal;
0194     } else {
0195       valid = current.Top()->GetUnplacedVolume()->Normal(localpoint, normal);
0196     }
0197     if (valid) normal = transform.InverseTransformDirection(normal);
0198     return valid;
0199   }
0200 
0201   /**
0202    * @brief Compute a bounded approach step without changing the navigation state.
0203    * @param globalpoint Point in global coordinates and inside @p in_state.
0204    * @param globaldir Unit direction in global coordinates.
0205    * @param step_limit Maximum requested step.
0206    * @param in_state Current navigation state.
0207    * @return Step limited by the next daughter approach or by @p step_limit.
0208    */
0209   VECCORE_ATT_HOST_DEVICE
0210   static VECGEOM_FORCE_INLINE Precision ComputeStepToApproachNextVolume(Vector3D<Precision> const &globalpoint,
0211                                                                         Vector3D<Precision> const &globaldir,
0212                                                                         Precision step_limit,
0213                                                                         vecgeom::NavigationState const &in_state)
0214   {
0215     return ComputeStepToApproachNextVolumeImpl(globalpoint, globaldir, step_limit, in_state);
0216   }
0217 
0218   /**
0219    * @brief Complete relocation after `ComputeStepAndNextVolume()`.
0220    * @param globalpoint Track endpoint in global coordinates.
0221    * @param globaldir Track direction in global coordinates.
0222    * @param[in,out] state Boundary state to descend through coincident volumes.
0223    */
0224   VECCORE_ATT_HOST_DEVICE
0225   static VECGEOM_FORCE_INLINE void RelocateToNextVolume(Vector3D<Precision> const &globalpoint,
0226                                                         Vector3D<Precision> const &globaldir,
0227                                                         vecgeom::NavigationState &state)
0228   {
0229     RelocateToNextVolumeImpl(globalpoint, globaldir, state);
0230   }
0231 
0232   /** @} */
0233 
0234 private:
0235   template <typename Real_t>
0236   friend class ::vgbrep::protonav::BVHSurfNavigator;
0237   friend class BVHSafetyEstimator;
0238 
0239 // to avoid changing the user code via templates, the precision is chosen at compile-time in the BVHManager and
0240 // BVHNavigator
0241 #ifdef VECGEOM_BVH_SINGLE
0242   using Real_t = float;
0243 #else
0244   using Real_t = double;
0245 #endif
0246 
0247   using Self_t = BVHNavigator;
0248 
0249   /// Host Safety scans up to this many boxes directly to avoid stack and internal-node overhead.
0250   static constexpr int kDirectSafetyBoxThreshold = 8;
0251 
0252   /** Box-traversal counters collected by the instrumented daughter ray query. */
0253   struct IntersectStatistics {
0254     long primitiveBoxTests{0};     ///< Primitive AABBs tested in visited leaves.
0255     long visitedLeaves{0};         ///< Leaf nodes reached by traversal.
0256     long cutNodes{0};              ///< Root-node rejections.
0257     long scheduledNodes{0};        ///< Child nodes whose AABBs intersect the ray.
0258     long intersectedBoxes{0};      ///< Primitive AABBs intersecting the ray.
0259     long deferredNodes{0};         ///< Far children deferred on the traversal stack.
0260     long prunableDeferredNodes{0}; ///< Deferred children beyond a later reduced step.
0261     long maximumStackDepth{0};     ///< Maximum number of deferred nodes.
0262   };
0263 
0264   /** Box-traversal counters collected by the instrumented daughter Safety query. */
0265   struct SafetyStatistics {
0266     long visitedNodes{0};      ///< Nodes removed from the traversal stack.
0267     long visitedLeaves{0};     ///< Leaf nodes reached by traversal.
0268     long primitiveBoxTests{0}; ///< Primitive AABB Safety evaluations.
0269     long relevantBoxes{0};     ///< Primitive AABBs closer than the current bound.
0270     long cutNodes{0};          ///< Nodes rejected by the current Safety bound.
0271   };
0272 
0273   VECCORE_ATT_HOST_DEVICE
0274   static auto GetBVH(int logicalVolumeId) { return vecgeom::BVHManager::GetBVH(logicalVolumeId); }
0275 
0276   /// @tparam conditional_exclusion If true, a daughter at a non-positive distance is refused when it is the excluded
0277   /// one or when the ray is leaving it.
0278   template <bool collect_statistics, typename Navigator, bool conditional_exclusion = false, typename BVHReal_t,
0279             typename Real_i>
0280   VECCORE_ATT_HOST_DEVICE static void CheckDaughterIntersectionsImpl(
0281       const vecgeom::IndexedBVH<BVHReal_t> &bvh, const Vector3D<Real_i> &localpoint, const Vector3D<Real_i> &localdir,
0282       Real_i &step, long const last_exited_id, long &hitcandidate_index, IntersectStatistics *statistics = nullptr,
0283       long *candidate_calls = nullptr)
0284   {
0285     struct StackItem {
0286       unsigned int node;
0287       BVHReal_t approach;
0288     };
0289     using StackEntry = std::conditional_t<collect_statistics, StackItem, unsigned int>;
0290     StackEntry stack[vecgeom::IndexedBVH<BVHReal_t>::kTraversalStackSize];
0291     int stackSize = 0;
0292 
0293     if constexpr (collect_statistics) {
0294       VECGEOM_ASSERT(statistics != nullptr);
0295       *statistics = IntersectStatistics{};
0296     }
0297 
0298     const bool mapped = bvh.HasDaughterMap();
0299     const Vector3D<BVHReal_t> point(static_cast<BVHReal_t>(localpoint[0]), static_cast<BVHReal_t>(localpoint[1]),
0300                                     static_cast<BVHReal_t>(localpoint[2]));
0301     const Vector3D<BVHReal_t> invDirection(static_cast<BVHReal_t>(1.) / vecgeom::NonZero(localdir[0]),
0302                                            static_cast<BVHReal_t>(1.) / vecgeom::NonZero(localdir[1]),
0303                                            static_cast<BVHReal_t>(1.) / vecgeom::NonZero(localdir[2]));
0304     // CUDA uses the direction-sign bits to select near/far slab endpoints.
0305     // The host predicate uses fixed endpoint loads; inlining removes this unused value there.
0306     const unsigned int octant = (invDirection[0] < BVHReal_t(0.) ? 1u : 0u) |
0307                                 (invDirection[1] < BVHReal_t(0.) ? 2u : 0u) |
0308                                 (invDirection[2] < BVHReal_t(0.) ? 4u : 0u);
0309     BVHReal_t bvhStep         = static_cast<BVHReal_t>(step);
0310     BVHReal_t rootApproach;
0311     if (!bvh.IntersectNode(0, point, invDirection, octant, bvhStep, rootApproach)) {
0312       if constexpr (collect_statistics) ++statistics->cutNodes;
0313       return;
0314     }
0315 
0316     auto const *nodes  = bvh.GetNodes();
0317     auto const *primId = bvh.GetPrimId();
0318     unsigned int top   = 0;
0319     for (;;) {
0320       while (!nodes[top].IsLeaf()) {
0321         const unsigned int childL = nodes[top].first;
0322         const unsigned int childR = childL + 1;
0323         BVHReal_t approachL, approachR;
0324         const bool hitL = bvh.IntersectNode(childL, point, invDirection, octant, bvhStep, approachL);
0325         const bool hitR = bvh.IntersectNode(childR, point, invDirection, octant, bvhStep, approachR);
0326         if constexpr (collect_statistics)
0327           statistics->scheduledNodes += static_cast<long>(hitL) + static_cast<long>(hitR);
0328 
0329         if (hitL) {
0330           // Visit the closer child first so exact hits reduce bvhStep before the deferred subtree.
0331           unsigned int near = childL;
0332           if (hitR) {
0333             unsigned int far   = childR;
0334             BVHReal_t farEntry = approachR;
0335             if (approachR < approachL) {
0336               near     = childR;
0337               far      = childL;
0338               farEntry = approachL;
0339             }
0340             if constexpr (collect_statistics) {
0341               stack[stackSize++] = StackItem{far, farEntry};
0342               ++statistics->deferredNodes;
0343               statistics->maximumStackDepth = vecgeom::Max(statistics->maximumStackDepth, long(stackSize));
0344             } else {
0345               stack[stackSize++] = far;
0346             }
0347           }
0348           top = near;
0349         } else if (hitR) {
0350           top = childR;
0351         } else {
0352           goto pop;
0353         }
0354       }
0355 
0356       if constexpr (collect_statistics) ++statistics->visitedLeaves;
0357       for (int i = 0; i < nodes[top].count; ++i) {
0358         if constexpr (collect_statistics) ++statistics->primitiveBoxTests;
0359         const int boxId = primId[nodes[top].first + i];
0360         BVHReal_t boxApproach;
0361         if (!bvh.IntersectBox(boxId, point, invDirection, bvhStep, boxApproach)) continue;
0362         if constexpr (collect_statistics) ++statistics->intersectedBoxes;
0363 
0364         const int prim      = bvh.GetDaughterId(boxId);
0365         const bool excluded = last_exited_id >= 0 && Navigator::SkipItem(bvh.GetRootId(), prim, last_exited_id);
0366         if constexpr (!conditional_exclusion) {
0367           if (excluded) continue;
0368         }
0369         if constexpr (collect_statistics) {
0370           if (candidate_calls) ++*candidate_calls;
0371         }
0372 
0373         const auto approach = static_cast<Real_i>(boxApproach);
0374         Real_i dist;
0375         if (!mapped) {
0376           dist =
0377               Navigator::CandidateDistanceToIn(bvh.GetRootId(), prim, localpoint + approach * localdir, localdir, step);
0378           if (dist > Real_i(0.)) dist += approach;
0379         } else if (conditional_exclusion) {
0380           // Take the distance from the original point: a later split box can start inside a refused daughter, or
0381           // in its hole, and the distance from there would accept it again.
0382           dist = Navigator::CandidateDistanceToIn(bvh.GetRootId(), prim, localpoint, localdir, step);
0383         } else {
0384           dist = Navigator::CandidateDistanceToIn(bvh.GetRootId(), prim, localpoint + approach * localdir, localdir,
0385                                                   vecgeom::Max(step - approach, Real_i(0.)));
0386           if (dist < Real_i(0.)) dist = Real_i(0.);
0387           dist += approach;
0388         }
0389         if (dist < step) {
0390           if constexpr (conditional_exclusion) {
0391             // As SimpleABBoxNavigator: at a non-positive distance refuse the excluded daughter and any daughter
0392             // the ray is leaving.
0393             if (dist <= Real_i(0.) &&
0394                 (excluded || Navigator::CandidateLeaves(bvh.GetRootId(), prim, localpoint, localdir)))
0395               continue;
0396           }
0397           dist               = vecgeom::Max(dist, Real_i(0.));
0398           step               = dist;
0399           bvhStep            = static_cast<BVHReal_t>(dist);
0400           hitcandidate_index = prim;
0401         }
0402       }
0403 
0404     pop:
0405       if (stackSize == 0) return;
0406       if constexpr (collect_statistics) {
0407         const auto deferred = stack[--stackSize];
0408         if (deferred.approach > bvhStep) ++statistics->prunableDeferredNodes;
0409         top = deferred.node;
0410       } else {
0411         top = stack[--stackSize];
0412       }
0413     }
0414   }
0415 
0416   template <bool collect_statistics, typename Navigator, typename BVHReal_t>
0417   VECCORE_ATT_HOST_DEVICE static Precision ComputeBVHSafetyImpl(const vecgeom::IndexedBVH<BVHReal_t> &bvh,
0418                                                                 Vector3D<Precision> const &localpoint, Precision safety,
0419                                                                 Precision limit, Precision min_valid_safety,
0420                                                                 SafetyStatistics *statistics = nullptr,
0421                                                                 long *limit_shortcuts        = nullptr,
0422                                                                 long *candidate_calls        = nullptr)
0423   {
0424     const Vector3D<BVHReal_t> point(static_cast<BVHReal_t>(localpoint[0]), static_cast<BVHReal_t>(localpoint[1]),
0425                                     static_cast<BVHReal_t>(localpoint[2]));
0426     if constexpr (collect_statistics) {
0427       VECGEOM_ASSERT(statistics != nullptr);
0428       *statistics = SafetyStatistics{};
0429     }
0430 
0431 #ifndef VECCORE_CUDA_DEVICE_COMPILATION
0432     if constexpr (!collect_statistics) {
0433       // For small CPU hierarchies, one root rejection plus a direct box scan is
0434       // cheaper than internal-node tests and stack traffic. CUDA retains the tree path.
0435       if (bvh.GetRootNChild() <= kDirectSafetyBoxThreshold) {
0436         if (static_cast<Precision>(bvh.NodeSafetySqr(0, point)) > safety * safety) return safety;
0437         for (int index = 0; index < bvh.GetRootNChild(); ++index) {
0438           const int boxId           = bvh.GetPrimId()[index];
0439           const Precision boxSafety = bvh.BoxSafety(boxId, localpoint);
0440           if (boxSafety >= safety) continue;
0441           if (boxSafety > limit) {
0442             safety = vecgeom::Min(safety, boxSafety);
0443             continue;
0444           }
0445           const int prim       = bvh.GetDaughterId(boxId);
0446           const Precision dist = Navigator::CandidateSafetyToIn(bvh.GetRootId(), prim, localpoint);
0447           if (dist > min_valid_safety) safety = vecgeom::Min(safety, dist);
0448         }
0449         return safety;
0450       }
0451     }
0452 #endif
0453 
0454     unsigned int stack[vecgeom::IndexedBVH<BVHReal_t>::kTraversalStackSize];
0455     int stackSize      = 1;
0456     stack[0]           = 0;
0457     auto const *nodes  = bvh.GetNodes();
0458     auto const *primId = bvh.GetPrimId();
0459 
0460     while (stackSize > 0) {
0461       const unsigned int id = stack[--stackSize];
0462       if constexpr (collect_statistics) ++statistics->visitedNodes;
0463       if (static_cast<Precision>(bvh.NodeSafetySqr(id, point)) > safety * safety) {
0464         if constexpr (collect_statistics) ++statistics->cutNodes;
0465         continue;
0466       }
0467 
0468       if (nodes[id].IsLeaf()) {
0469         if constexpr (collect_statistics) ++statistics->visitedLeaves;
0470         for (int i = 0; i < nodes[id].count; ++i) {
0471           if constexpr (collect_statistics) ++statistics->primitiveBoxTests;
0472           const int boxId           = primId[nodes[id].first + i];
0473           const Precision boxSafety = bvh.BoxSafety(boxId, localpoint);
0474           if (boxSafety >= safety) continue;
0475           if constexpr (collect_statistics) ++statistics->relevantBoxes;
0476           if (boxSafety > limit) {
0477             if constexpr (collect_statistics) {
0478               if (limit_shortcuts) ++*limit_shortcuts;
0479             }
0480             safety = vecgeom::Min(safety, boxSafety);
0481             continue;
0482           }
0483           if constexpr (collect_statistics) {
0484             if (candidate_calls) ++*candidate_calls;
0485           }
0486           const int prim       = bvh.GetDaughterId(boxId);
0487           const Precision dist = Navigator::CandidateSafetyToIn(bvh.GetRootId(), prim, localpoint);
0488           if (dist > min_valid_safety) safety = vecgeom::Min(safety, dist);
0489         }
0490       } else {
0491         const unsigned int childL = nodes[id].first;
0492         const unsigned int childR = childL + 1;
0493         const BVHReal_t safetyL   = bvh.NodeSafetySqr(childL, point);
0494         const BVHReal_t safetyR   = bvh.NodeSafetySqr(childR, point);
0495         const Precision limitSqr  = safety * safety;
0496         const bool traverseL      = static_cast<Precision>(safetyL) < limitSqr;
0497         const bool traverseR      = static_cast<Precision>(safetyR) < limitSqr;
0498         if (safetyR < safetyL) {
0499           if (traverseL) stack[stackSize++] = childL;
0500           if (traverseR) stack[stackSize++] = childR;
0501         } else {
0502           if (traverseR) stack[stackSize++] = childR;
0503           if (traverseL) stack[stackSize++] = childL;
0504         }
0505       }
0506     }
0507     return safety;
0508   }
0509 
0510 protected:
0511   // Exact daughter operations used by the navigator traversal and specialized derived adapters.
0512 
0513   /*
0514    * @param[in] aLVIndex Global index of a LogicalVolume
0515    * @param[in] index Index within the list of daughters of the specified LogicalVolume
0516    * @returns The PlacedVolume defined by @p aLVIndex and @p index
0517    */
0518   VECCORE_ATT_HOST_DEVICE
0519   static VECGEOM_FORCE_INLINE Daughter GetPlacedVolume(int aLVIndex, int index)
0520   {
0521 #ifdef VECCORE_CUDA_DEVICE_COMPILATION
0522     VECGEOM_VALIDATE(vecgeom::globaldevicegeomdata::gDeviceLogicalVolumes != nullptr,
0523                      << "Logical volumes not copied to device");
0524     return vecgeom::globaldevicegeomdata::gDeviceLogicalVolumes[aLVIndex].GetDaughters()[index];
0525 #else
0526 #ifndef VECCORE_CUDA
0527     return vecgeom::GeoManager::Instance().GetLogicalVolume(aLVIndex)->GetDaughters()[index];
0528 #else
0529     // this is the case when we compile with nvcc for host side
0530     VECGEOM_VALIDATE(false, << "reached unimplement code");
0531     (void)index; // avoid unused parameter warning.
0532     (void)aLVIndex;
0533     return nullptr;
0534 #endif
0535 #endif
0536   }
0537 
0538   /*
0539    * @param[in] global_index Global index of a PlacedVolume
0540    * @returns The PlacedVolume with global index @p global_index
0541    */
0542   VECCORE_ATT_HOST_DEVICE
0543   static VECGEOM_FORCE_INLINE vecgeom::VPlacedVolume *GetPlacedVolume(int global_index)
0544   {
0545 #ifdef VECCORE_CUDA_DEVICE_COMPILATION
0546     VECGEOM_VALIDATE(vecgeom::globaldevicegeomdata::gCompactPlacedVolBuffer != nullptr,
0547                      << "Placed volumes not copied to device");
0548     return &vecgeom::globaldevicegeomdata::gCompactPlacedVolBuffer[global_index];
0549 #else
0550 #ifndef VECCORE_CUDA
0551     return vecgeom::GeoManager::Instance().GetPlacedVolume(global_index);
0552 #else
0553     // this is the case when we compile with nvcc for host side
0554     VECGEOM_VALIDATE(false, << "reached unimplement code");
0555     (void)global_index; // avoid unused parameter warning.
0556     return nullptr;
0557 #endif
0558 #endif
0559   }
0560 
0561   /*
0562    * @param[in] aLVIndex Global index of a LogicalVolume
0563    * @param[in] index Index within the list of daughters of the specified LogicalVolume
0564    * @param[in] localpoint Point in the local coordinates of the LV specified by @aLVIndex
0565    * @returns The safety to in to the PlacedVolume defined by @p aLVIndex and @p index for the point @p localpoint
0566    */
0567   VECCORE_ATT_HOST_DEVICE
0568   static Precision CandidateSafetyToIn(int aLVIndex, int index, Vector3D<Precision> localpoint)
0569   {
0570     return GetPlacedVolume(aLVIndex, index)->SafetyToIn(localpoint);
0571   };
0572 
0573   /*
0574    * @param[in] aLVIndex Global index of a LogicalVolume
0575    * @param[in] index Index within the list of daughters of the specified LogicalVolume
0576    * @param[in] localpoint Point in the local coordinates of the LV specified by @aLVIndex
0577    * @param[in] localdir Direction in the local coordinates of the LV specified by @aLVIndex
0578    * @param[in] step Maximum step length
0579    * @returns The distance to in to the PlacedVolume defined by @p aLVIndex and @p index for the point @p localpoint
0580    * and direction @p localdir
0581    */
0582   VECCORE_ATT_HOST_DEVICE
0583   static Precision CandidateDistanceToIn(int aLVIndex, int index, Vector3D<Precision> localpoint,
0584                                          Vector3D<Precision> localdir, Precision step)
0585   {
0586     Daughter vol = GetPlacedVolume(aLVIndex, index);
0587     return vol->DistanceToIn(localpoint, localdir, step);
0588   };
0589 
0590   /*
0591    * @param[in] aLVIndex Global index of a LogicalVolume
0592    * @param[in] index Index within the list of daughters of the specified LogicalVolume
0593    * @param[in] localpoint Point in the local coordinates of the LV specified by @aLVIndex, on or inside the daughter
0594    * @param[in] localdir Direction in the local coordinates of the LV specified by @aLVIndex
0595    * @returns Whether the surface normal of the PlacedVolume defined by @p aLVIndex and @p index at @p localpoint
0596    * has a positive projection on @p localdir, that is whether the ray is leaving it
0597    */
0598   VECCORE_ATT_HOST_DEVICE
0599   static bool CandidateLeaves(int aLVIndex, int index, Vector3D<Precision> localpoint, Vector3D<Precision> localdir)
0600   {
0601     Vector3D<Precision> normal;
0602     GetPlacedVolume(aLVIndex, index)->Normal(localpoint, normal);
0603     return normal.Dot(localdir) > 0.;
0604   }
0605 
0606   /*
0607    * @param[in] aLVIndex Global index of a LogicalVolume
0608    * @param[in] index Index within the list of daughters of the specified LogicalVolume
0609    * @param[in] localpoint Point in the local coordinates of the LV specified by @aLVIndex
0610    * @param[out] daughterlocalpoint Point in the local coordinates of the PlacedVolume defined by
0611    * @p aLVIndex and @p index
0612    * @returns Whether @localpoint falls within the PlacedVolume defined by @p aLVIndex and @p index
0613    */
0614   VECCORE_ATT_HOST_DEVICE
0615   static vecgeom::Inside_t CandidateInside(int aLVIndex, int index, Vector3D<Precision> const &localpoint,
0616                                            Vector3D<Precision> &daughterlocalpoint)
0617   {
0618     auto daughter      = GetPlacedVolume(aLVIndex, index);
0619     daughterlocalpoint = daughter->GetTransformation()->template Transform<Precision>(localpoint);
0620     return daughter->GetUnplacedVolume()->Inside(daughterlocalpoint);
0621   };
0622 
0623   /*
0624    * @param[in] aLVIndex Global index of a LogicalVolume
0625    * @param[in] index Index within the list of daughters of the specified LogicalVolume
0626    * @param[in] localpoint Point in the local coordinates of the LV specified by @aLVIndex
0627    * @param[out] daughterlocalpoint Point in the local coordinates of the PlacedVolume defined by
0628    * @p aLVIndex and @p index
0629    * @returns Whether @localpoint falls within the PlacedVolume defined by @p aLVIndex and @p index
0630    */
0631   VECCORE_ATT_HOST_DEVICE
0632   static bool CandidateContains(int aLVIndex, int index, Vector3D<Precision> const &localpoint,
0633                                 Vector3D<Precision> &daughterlocalpoint)
0634   {
0635     auto inside = CandidateInside(aLVIndex, index, localpoint, daughterlocalpoint);
0636     return inside != EnumInside::kOutside;
0637   };
0638 
0639   /*
0640    * @param[in] aLVIndex Global index of a LogicalVolume
0641    * @param[in] index Index within the list of daughters of the specified LogicalVolume
0642    * @param[in] localpoint Point in the local coordinates of the LV specified by @aLVIndex
0643    * @param[in] localdir Direction in the local coordinates of the LV specified by @aLVIndex
0644    * @returns The distance to in to the Bounding Box of the PlacedVolume defined by @p aLVIndex
0645    * and @p index for the point @p localpoint and direction @p localdir
0646    */
0647   VECCORE_ATT_HOST_DEVICE
0648   static Precision CandidateApproachSolid(int aLVIndex, int index, Vector3D<Precision> localpoint,
0649                                           Vector3D<Precision> localdir)
0650   {
0651     auto vol                            = GetPlacedVolume(aLVIndex, index);
0652     vecgeom::Transformation3D const *tr = vol->GetTransformation();
0653     Vector3D<Precision> pv_localpoint   = tr->Transform(localpoint);
0654     Vector3D<Precision> pv_localdir     = tr->TransformDirection(localdir);
0655     Vector3D<Precision> pv_invlocaldir(1.0 / vecgeom::NonZero(pv_localdir[0]), 1.0 / vecgeom::NonZero(pv_localdir[1]),
0656                                        1.0 / vecgeom::NonZero(pv_localdir[2]));
0657     return vol->GetUnplacedVolume()->ApproachSolid(pv_localpoint, pv_invlocaldir);
0658   };
0659 
0660   /*
0661    * Used by the BVH to determine if it needs to skip checking a placed volume. The global index of the volume
0662    * defined by @p aLVIndex and @p index can only be accessed from the navigator
0663    * @param[in] aLVIndex Global index of a LogicalVolume
0664    * @param[in] index Index within the list of daughters of the specified LogicalVolume
0665    * @param[in] global_id Global id of a PLacedVolume
0666    * @returns Whether the global id of the PlacedVolume defined by @p aLVIndex and @p index is the same as @p global_id
0667    */
0668   VECCORE_ATT_HOST_DEVICE
0669   static VECGEOM_FORCE_INLINE bool SkipItem(int aLVIndex, int index, long const global_id)
0670   {
0671     return (global_id == GetPlacedVolume(aLVIndex, index)->id());
0672   }
0673 
0674 public:
0675   /** @name Internal component interface
0676    *  These traversal operations are shared with VecGeom safety and surface-navigation components.
0677    *  @{ */
0678 
0679   /**
0680    * @brief Find the nearest daughter entry along a bounded IndexedBVH ray query.
0681    *
0682    * Primitive-box ids are mapped before the exact query. The exact query starts
0683    * at the box entry distance; mapped boxes clamp a negative residual distance
0684    * because a split box may begin inside its daughter.
0685    *
0686    * @tparam Navigator Static adapter providing exact daughter operations.
0687    * @tparam BVHReal_t Scalar type stored by the hierarchy.
0688    * @tparam Real_i Scalar query precision.
0689    * @param bvh Box hierarchy for the mother volume.
0690    * @param localpoint Ray origin in mother-local coordinates.
0691    * @param localdir Ray direction in mother-local coordinates.
0692    * @param[in,out] step Maximum step on input; nearest accepted entry on output.
0693    * @param last_exited_id Placed-volume id excluded from immediate re-entry, or
0694    *                       a negative value when no exclusion applies.
0695    * @param[out] hitcandidate_index Daughter index of the nearest accepted hit;
0696    *                                unchanged when no closer daughter is found.
0697    */
0698   template <typename Navigator, typename BVHReal_t, typename Real_i>
0699   VECCORE_ATT_HOST_DEVICE static void CheckDaughterIntersections(const vecgeom::IndexedBVH<BVHReal_t> &bvh,
0700                                                                  const Vector3D<Real_i> &localpoint,
0701                                                                  const Vector3D<Real_i> &localdir, Real_i &step,
0702                                                                  long const last_exited_id, long &hitcandidate_index)
0703   {
0704     CheckDaughterIntersectionsImpl<false, Navigator>(bvh, localpoint, localdir, step, last_exited_id,
0705                                                      hitcandidate_index);
0706   }
0707 
0708   /**
0709    * @brief CheckDaughterIntersections for Geant4: at a non-positive distance, refuses @p blocked_id and any
0710    * daughter the ray is leaving, as SimpleABBoxNavigator does.
0711    * @param blocked_id Placed-volume id refused at a non-positive distance, or -1 for none.
0712    */
0713   template <typename Navigator, typename BVHReal_t, typename Real_i>
0714   VECCORE_ATT_HOST_DEVICE static void CheckDaughterIntersectionsBlocked(const vecgeom::IndexedBVH<BVHReal_t> &bvh,
0715                                                                         const Vector3D<Real_i> &localpoint,
0716                                                                         const Vector3D<Real_i> &localdir, Real_i &step,
0717                                                                         long const blocked_id, long &hitcandidate_index)
0718   {
0719     CheckDaughterIntersectionsImpl<false, Navigator, true>(bvh, localpoint, localdir, step, blocked_id,
0720                                                            hitcandidate_index);
0721   }
0722 
0723   /**
0724    * @brief Run `CheckDaughterIntersections()` while collecting traversal work.
0725    *
0726    * This diagnostic query preserves the candidate semantics of the normal
0727    * query but is not used by navigation.
0728    *
0729    * @tparam Navigator Static adapter providing exact daughter operations.
0730    * @tparam BVHReal_t Scalar type stored by the hierarchy.
0731    * @tparam Real_i Scalar query precision.
0732    * @param bvh Box hierarchy for the mother volume.
0733    * @param localpoint Ray origin in mother-local coordinates.
0734    * @param localdir Ray direction in mother-local coordinates.
0735    * @param[in,out] step Maximum step on input; nearest accepted entry on output.
0736    * @param last_exited_id Placed-volume id excluded from immediate re-entry.
0737    * @param[out] hitcandidate_index Daughter index of the nearest accepted hit.
0738    * @param[out] total_visited_children Primitive AABB tests.
0739    * @param[out] total_visited_leaves Visited leaf nodes.
0740    * @param[out] total_cut_nodes Root-node rejections.
0741    * @param[out] total_scheduled_nodes Intersected child nodes.
0742    * @param[out] total_intersected_children Intersected primitive AABBs, when requested.
0743    * @param[out] total_candidate_calls Exact daughter calls, when requested.
0744    * @param[out] total_deferred_nodes Deferred far children, when requested.
0745    * @param[out] total_prunable_deferred_nodes Deferred children beyond a reduced step, when requested.
0746    * @param[out] maximum_stack_depth Maximum deferred-node count, when requested.
0747    */
0748   template <typename Navigator, typename BVHReal_t, typename Real_i>
0749   VECCORE_ATT_HOST_DEVICE static void CheckDaughterIntersectionsBenchmark(
0750       const vecgeom::IndexedBVH<BVHReal_t> &bvh, const Vector3D<Real_i> &localpoint, const Vector3D<Real_i> &localdir,
0751       Real_i &step, long const last_exited_id, long &hitcandidate_index, long &total_visited_children,
0752       long &total_visited_leaves, long &total_cut_nodes, long &total_scheduled_nodes,
0753       long *total_intersected_children = nullptr, long *total_candidate_calls = nullptr,
0754       long *total_deferred_nodes = nullptr, long *total_prunable_deferred_nodes = nullptr,
0755       long *maximum_stack_depth = nullptr)
0756   {
0757     IntersectStatistics statistics;
0758     if (total_candidate_calls) *total_candidate_calls = 0;
0759     CheckDaughterIntersectionsImpl<true, Navigator>(bvh, localpoint, localdir, step, last_exited_id, hitcandidate_index,
0760                                                     &statistics, total_candidate_calls);
0761 
0762     total_visited_children = statistics.primitiveBoxTests;
0763     total_visited_leaves   = statistics.visitedLeaves;
0764     total_cut_nodes        = statistics.cutNodes;
0765     total_scheduled_nodes  = statistics.scheduledNodes;
0766     if (total_intersected_children) *total_intersected_children = statistics.intersectedBoxes;
0767     if (total_deferred_nodes) *total_deferred_nodes = statistics.deferredNodes;
0768     if (total_prunable_deferred_nodes) *total_prunable_deferred_nodes = statistics.prunableDeferredNodes;
0769     if (maximum_stack_depth) *maximum_stack_depth = statistics.maximumStackDepth;
0770   }
0771 
0772   /**
0773    * @brief Reduce @p step to the nearest approached daughter solid.
0774    *
0775    * This method traverses primitive boxes near-first, maps each candidate, and
0776    * applies the reduced step immediately to prune the remaining traversal.
0777    *
0778    * @tparam Navigator Static adapter providing exact daughter operations.
0779    * @tparam BVHReal_t Scalar type stored by the hierarchy.
0780    * @param bvh Box hierarchy for the mother volume.
0781    * @param localpoint Ray origin in mother-local coordinates.
0782    * @param localdir Ray direction in mother-local coordinates.
0783    * @param[in,out] step Maximum approach on input; nearest accepted approach on output.
0784    * @param last_exited_id Placed-volume id excluded at non-positive distance.
0785    */
0786   template <typename Navigator, typename BVHReal_t>
0787   VECCORE_ATT_HOST_DEVICE static void ApproachNextDaughter(const vecgeom::IndexedBVH<BVHReal_t> &bvh,
0788                                                            Vector3D<Precision> const &localpoint,
0789                                                            Vector3D<Precision> const &localdir, Precision &step,
0790                                                            long const last_exited_id)
0791   {
0792     unsigned int stack[vecgeom::IndexedBVH<BVHReal_t>::kTraversalStackSize];
0793     int stackSize = 0;
0794     const Vector3D<BVHReal_t> point(static_cast<BVHReal_t>(localpoint[0]), static_cast<BVHReal_t>(localpoint[1]),
0795                                     static_cast<BVHReal_t>(localpoint[2]));
0796     const Vector3D<BVHReal_t> invDirection(static_cast<BVHReal_t>(1.) / vecgeom::NonZero(localdir[0]),
0797                                            static_cast<BVHReal_t>(1.) / vecgeom::NonZero(localdir[1]),
0798                                            static_cast<BVHReal_t>(1.) / vecgeom::NonZero(localdir[2]));
0799     const unsigned int octant = (invDirection[0] < BVHReal_t(0.) ? 1u : 0u) |
0800                                 (invDirection[1] < BVHReal_t(0.) ? 2u : 0u) |
0801                                 (invDirection[2] < BVHReal_t(0.) ? 4u : 0u);
0802     BVHReal_t bvhStep         = static_cast<BVHReal_t>(step);
0803     BVHReal_t approach;
0804     if (!bvh.IntersectNode(0, point, invDirection, octant, bvhStep, approach)) return;
0805 
0806     auto const *nodes  = bvh.GetNodes();
0807     auto const *primId = bvh.GetPrimId();
0808     unsigned int top   = 0;
0809     for (;;) {
0810       while (!nodes[top].IsLeaf()) {
0811         const unsigned int childL = nodes[top].first;
0812         const unsigned int childR = childL + 1;
0813         BVHReal_t approachL, approachR;
0814         const bool hitL = bvh.IntersectNode(childL, point, invDirection, octant, bvhStep, approachL);
0815         const bool hitR = bvh.IntersectNode(childR, point, invDirection, octant, bvhStep, approachR);
0816         if (hitL) {
0817           unsigned int near = childL;
0818           if (hitR) {
0819             unsigned int far = childR;
0820             if (approachR < approachL) {
0821               near = childR;
0822               far  = childL;
0823             }
0824             stack[stackSize++] = far;
0825           }
0826           top = near;
0827         } else if (hitR) {
0828           top = childR;
0829         } else {
0830           goto pop;
0831         }
0832       }
0833 
0834       for (int i = 0; i < nodes[top].count; ++i) {
0835         const int boxId = primId[nodes[top].first + i];
0836         if (!bvh.IntersectBox(boxId, point, invDirection, bvhStep, approach)) continue;
0837         const int prim  = bvh.GetDaughterId(boxId);
0838         const auto dist = Navigator::CandidateApproachSolid(bvh.GetRootId(), prim, localpoint, localdir);
0839         if (dist < step && !(dist <= Precision(0.) && Navigator::SkipItem(bvh.GetRootId(), prim, last_exited_id))) {
0840           step    = dist;
0841           bvhStep = static_cast<BVHReal_t>(dist);
0842         }
0843       }
0844 
0845     pop:
0846       if (stackSize == 0) return;
0847       top = stack[--stackSize];
0848     }
0849   }
0850 
0851   /**
0852    * @brief Reduce a Safety bound against mapped primitive candidates.
0853    *
0854    * A primitive whose conservative AABB Safety exceeds @p limit can reduce the
0855    * result without an exact item query. Other accepted boxes are mapped before
0856    * the exact query.
0857    *
0858    * @tparam Navigator Static adapter providing exact item Safety operations.
0859    * @tparam BVHReal_t Scalar type stored by the hierarchy.
0860    * @param bvh Box hierarchy for the owner.
0861    * @param localpoint Point in owner-local coordinates.
0862    * @param safety Initial upper bound.
0863    * @param limit Accuracy limit for exact item calls.
0864    * @param min_valid_safety Ignore exact values at or below this value.
0865    * @return Minimum accepted item Safety or the input @p safety.
0866    */
0867   template <typename Navigator, typename BVHReal_t>
0868   VECCORE_ATT_HOST_DEVICE static Precision ComputeBVHSafety(const vecgeom::IndexedBVH<BVHReal_t> &bvh,
0869                                                             Vector3D<Precision> const &localpoint, Precision safety,
0870                                                             Precision limit            = InfinityLength<Precision>(),
0871                                                             Precision min_valid_safety = -InfinityLength<Precision>())
0872   {
0873     return ComputeBVHSafetyImpl<false, Navigator>(bvh, localpoint, safety, limit, min_valid_safety);
0874   }
0875 
0876   /**
0877    * @brief Run `ComputeBVHSafety()` while collecting traversal work.
0878    *
0879    * This diagnostic query uses the tree path on the CPU so its counters describe
0880    * actual nodes and leaves; it is not used by navigation.
0881    *
0882    * @tparam Navigator Static adapter providing exact item Safety operations.
0883    * @tparam BVHReal_t Scalar type stored by the hierarchy.
0884    * @param bvh Box hierarchy for the owner.
0885    * @param localpoint Point in owner-local coordinates.
0886    * @param safety Initial upper bound.
0887    * @param limit Accuracy limit for exact item calls.
0888    * @param min_valid_safety Ignore exact values at or below this value.
0889    * @param[out] visited_nodes Visited hierarchy nodes.
0890    * @param[out] visited_leaves Visited leaf nodes.
0891    * @param[out] primitive_box_tests Primitive AABB Safety evaluations.
0892    * @param[out] relevant_boxes Primitive AABBs closer than the current bound.
0893    * @param[out] limit_shortcuts AABB results accepted above @p limit.
0894    * @param[out] candidate_calls Exact item Safety calls.
0895    * @param[out] cut_nodes Nodes rejected by the current bound.
0896    * @return Reduced Safety.
0897    */
0898   template <typename Navigator, typename BVHReal_t>
0899   VECCORE_ATT_HOST_DEVICE static Precision ComputeSafetyBenchmark(
0900       const vecgeom::IndexedBVH<BVHReal_t> &bvh, Vector3D<Precision> const &localpoint, Precision safety,
0901       Precision limit, Precision min_valid_safety, long &visited_nodes, long &visited_leaves, long &primitive_box_tests,
0902       long &relevant_boxes, long &limit_shortcuts, long &candidate_calls, long &cut_nodes)
0903   {
0904     SafetyStatistics statistics;
0905     limit_shortcuts = 0;
0906     candidate_calls = 0;
0907     safety        = ComputeBVHSafetyImpl<true, Navigator>(bvh, localpoint, safety, limit, min_valid_safety, &statistics,
0908                                                           &limit_shortcuts, &candidate_calls);
0909     visited_nodes = statistics.visitedNodes;
0910     visited_leaves      = statistics.visitedLeaves;
0911     primitive_box_tests = statistics.primitiveBoxTests;
0912     relevant_boxes      = statistics.relevantBoxes;
0913     cut_nodes           = statistics.cutNodes;
0914     return safety;
0915   }
0916 
0917   /**
0918    * @brief Find the first non-excluded daughter containing @p localpoint.
0919    *
0920    * @tparam Navigator Static adapter providing exact daughter operations and ids.
0921    * @tparam BVHReal_t Scalar type stored by the hierarchy.
0922    * @param bvh Box hierarchy for the mother volume.
0923    * @param exclude_item_id Placed-volume id to skip, or a negative value.
0924    * @param localpoint Point in mother-local coordinates.
0925    * @param[out] container_id Placed-volume id of the containing daughter.
0926    * @param[out] daughterlocalpoint Point transformed into that daughter.
0927    * @return `kInside` or `kSurface` for the first accepted daughter, otherwise `kOutside`.
0928    */
0929   template <typename Navigator, typename BVHReal_t>
0930   VECCORE_ATT_HOST_DEVICE static vecgeom::Inside_t LevelInside(const vecgeom::IndexedBVH<BVHReal_t> &bvh,
0931                                                                long const exclude_item_id,
0932                                                                Vector3D<Precision> const &localpoint,
0933                                                                long &container_id,
0934                                                                Vector3D<Precision> &daughterlocalpoint)
0935   {
0936     vecgeom::Inside_t result = kOutside;
0937     const Vector3D<BVHReal_t> point(static_cast<BVHReal_t>(localpoint[0]), static_cast<BVHReal_t>(localpoint[1]),
0938                                     static_cast<BVHReal_t>(localpoint[2]));
0939     if (!bvh.NodeContains(0, point)) return result;
0940 
0941     unsigned int stack[vecgeom::IndexedBVH<BVHReal_t>::kTraversalStackSize];
0942     int stackSize      = 0;
0943     auto const *nodes  = bvh.GetNodes();
0944     auto const *primId = bvh.GetPrimId();
0945     unsigned int top   = 0;
0946     for (;;) {
0947       while (!nodes[top].IsLeaf()) {
0948         const unsigned int childL = nodes[top].first;
0949         const unsigned int childR = childL + 1;
0950         const bool inL            = bvh.NodeContains(childL, point);
0951         const bool inR            = bvh.NodeContains(childR, point);
0952         if (inL) {
0953           if (inR) stack[stackSize++] = childR;
0954           top = childL;
0955         } else if (inR) {
0956           top = childR;
0957         } else {
0958           goto pop;
0959         }
0960       }
0961 
0962       for (int i = 0; i < nodes[top].count; ++i) {
0963         const int boxId = primId[nodes[top].first + i];
0964         if (!bvh.BoxContains(boxId, point)) continue;
0965         const int prim = bvh.GetDaughterId(boxId);
0966         if (Navigator::SkipItem(bvh.GetRootId(), prim, exclude_item_id)) continue;
0967         const auto inside = Navigator::CandidateInside(bvh.GetRootId(), prim, localpoint, daughterlocalpoint);
0968         if (inside == kOutside) continue;
0969         container_id = Navigator::ItemId(bvh.GetRootId(), prim);
0970         return inside;
0971       }
0972 
0973     pop:
0974       if (stackSize == 0) return result;
0975       top = stack[--stackSize];
0976     }
0977   }
0978 
0979   /** @} */
0980 
0981 protected:
0982   /** @name Navigation diagnostics
0983    *  Instrumented entry points used by validation and benchmarking.
0984    *  @{ */
0985 
0986   /** Test adapter exposing one IndexedBVH daughter-intersection query. */
0987   VECCORE_ATT_HOST_DEVICE
0988   static long TestBVHCheckDaughterIntersections(const vecgeom::IndexedBVH<Real_t> &bvh, Vector3D<Precision> &localpoint,
0989                                                 Vector3D<Precision> &localdir, Precision &bvhstep)
0990   {
0991     long hitcandidate_index = -1;
0992     long last_exited_id     = -1;
0993     CheckDaughterIntersections<Self_t>(bvh, localpoint, localdir, bvhstep, last_exited_id, hitcandidate_index);
0994     return hitcandidate_index;
0995   }
0996 
0997   VECCORE_ATT_HOST_DEVICE
0998   static long TestCheckDaughterIntersections(int logicalVolumeId, Vector3D<Precision> const &localpoint,
0999                                              Vector3D<Precision> const &localdir, Precision &bvhstep)
1000   {
1001     long hitcandidate_index = -1;
1002     auto const *bvh         = GetBVH(logicalVolumeId);
1003     CheckDaughterIntersections<Self_t>(*bvh, localpoint, localdir, bvhstep, -1, hitcandidate_index);
1004     return hitcandidate_index;
1005   }
1006 
1007   /** @} */
1008 
1009   /*
1010    * @param[in] aLVIndex Global index of a LogicalVolume
1011    * @param[in] index Index within the list of daughters of the specified LogicalVolume
1012    * @returns The global id of the PlacedVolume defined by @p aLVIndex and @p index
1013    */
1014   VECCORE_ATT_HOST_DEVICE
1015   static uint ItemId(int aLVIndex, int index) { return GetPlacedVolume(aLVIndex, index)->id(); }
1016 
1017 private:
1018   /** @name Point-location implementation
1019    *  These bodies resolve point-location queries using the internal BVH traversal.
1020    *  @{ */
1021 
1022   /**
1023    * @brief Locate the deepest daughter volume that contains a point, starting from a given placed volume.
1024    *
1025    * ## Coordinate frames
1026    * - **Input point** @p point is in the **parent frame of @p vol** (i.e. the same frame expected by
1027    *   `VPlacedVolume::Inside` for @p vol).
1028    * - The NavigationState @p path should point to the **parent frame of @p vol**.
1029    * @param[in]  vol
1030    *   The starting placed volume (the mother at which the descent begins). Must be non-null if @p top is true.
1031    * @param[in]  point
1032    *   Query point **in the parent frame of @p vol**.
1033    * @param[in,out] path
1034    *   Navigation state to be filled. Must start at the  **parent frame of @p vol**.
1035    * @param[in]  top
1036    *   If true, the function first validates that the point is inside @p vol. If false, a nullptr is returned
1037    * @param[in]  exclude
1038    *   Optional placed volume to exclude once during the descent (useful to avoid immediately
1039    *   re-entering a volume you just exited). The exclusion is applied only to the first BVH
1040    *   query and then cleared.
1041    * @return
1042    *   The deepest placed volume that contains the point, or `nullptr` if @p top is true and
1043    *   `vol->Inside(point)` reports outside. When the descent stops at @p vol (i.e. no daughter
1044    *   contains the point), returns @p vol.
1045    */
1046   VECCORE_ATT_HOST_DEVICE
1047   static Daughter LocatePointInImpl(vecgeom::VPlacedVolume const *vol, Vector3D<Precision> const &point,
1048                                     vecgeom::NavigationState &path, bool top,
1049                                     vecgeom::VPlacedVolume const *exclude = nullptr)
1050   {
1051 
1052     // optional check whether the point is inside the provided placed volume vol
1053     if (top) {
1054       // Must check the provided volume
1055       VECGEOM_ASSERT(vol != nullptr);
1056       auto inside = vol->Inside(point);
1057       if (inside == kOutside) return nullptr;
1058       // Set the boundary state to the path
1059       if (inside == kSurface) path.SetBoundaryState(true);
1060     }
1061 
1062     path.Push(vol);
1063 
1064     // transform the point into the reference frame of the `vol`
1065     Vector3D<Precision> currentpoint(vol->GetTransformation()->Transform<Precision>(point));
1066     Vector3D<Precision> daughterlocalpoint;
1067     long exclude_id = -1;
1068     long vol_id     = -1;
1069 
1070     for (auto v = vol; v->GetDaughters().size() > 0;) {
1071       auto bvh = GetBVH(v->GetLogicalVolume()->id());
1072 
1073       exclude_id = -1;
1074       if (exclude != nullptr) {
1075         exclude_id = exclude->id();
1076       }
1077       vol_id = -1;
1078 
1079       const auto inside = LevelInside<Self_t>(*bvh, exclude_id, currentpoint, vol_id, daughterlocalpoint);
1080       if (inside == kOutside) break;
1081       if (inside == kSurface) path.SetBoundaryState(true);
1082 
1083       currentpoint = daughterlocalpoint;
1084       // Update the current volume v
1085       v = GetPlacedVolume(vol_id);
1086       path.Push(v);
1087 
1088       // Only exclude the placed volume once since we could enter it again via a
1089       // different volume history.
1090       exclude = nullptr;
1091     }
1092 
1093     return path.Top();
1094   }
1095 
1096   /**
1097    * @brief Find new final NavigationState after a NavigationState has just been left (i.e., after exiting its corresponding top volume)
1098    * The function will climb up the NavigationStates until the point is inside, and then descend again to find the
1099    * deepest volume containing the point. The just exited volume will be skipped
1100    * @param[in]  localpoint   Point in the **local frame of the navigation state (path.Top())**
1101    * @param[in,out] path      Navigation state of the volume that was just left; updated to the new deepest containing path.
1102    * @return The deepest placed volume that contains the point (after re-location), or nullptr if no mother exists.
1103    */
1104   VECCORE_ATT_HOST_DEVICE
1105   static Daughter RelocatePointImpl(Vector3D<Precision> const &localpoint, vecgeom::NavigationState &path)
1106   {
1107     vecgeom::VPlacedVolume const *currentmother = path.Top();
1108     Daughter skip                               = nullptr;
1109     Vector3D<Precision> transformed             = localpoint;
1110     // continue to climb up the Navigation tree until a volume is found which contains the volume
1111     do {
1112       skip = currentmother;
1113       path.Pop();
1114       transformed   = currentmother->GetTransformation()->InverseTransform(transformed);
1115       currentmother = path.Top();
1116     } while (currentmother && (currentmother->IsAssembly() || !currentmother->UnplacedContains(transformed)));
1117 
1118     // first volume up the hierarchy is found that contains the point. Now descend to find the deepest state that
1119     // contains the point
1120     if (currentmother) {
1121       return LocatePointInNavState(transformed, path, false, skip);
1122     }
1123     return currentmother;
1124   }
1125 
1126   /**
1127    * @brief Update NavState path to the deepest state that contains given point starting from the given path.
1128    * @param[in]  localpoint
1129    *   localpoint **in the reference frame of @p path.**.
1130    * @param[in,out] path
1131    *   Starting NavigationState; output of the final NavigationState
1132    * @param[in]  top
1133    *   If true, the function first validates that the point is inside @p path. If false, a nullptr is returned
1134    * @param[in]  exclude
1135    *   Optional placed volume to exclude once during the descent
1136    * @return
1137    *   The final top-volume of the NavState after finding the deepest NavState that contains the point
1138    */
1139   VECCORE_ATT_HOST_DEVICE
1140   static Daughter LocatePointInNavStateImpl(Vector3D<Precision> const &localpoint, vecgeom::NavigationState &path,
1141                                             bool top, vecgeom::VPlacedVolume const *exclude = nullptr)
1142   {
1143 
1144     VECGEOM_ASSERT(path.Top() != nullptr);
1145 
1146     auto currentLogical = path.Top()->GetLogicalVolume();
1147     VECGEOM_ASSERT(currentLogical != nullptr);
1148 
1149     // optional check if point is inside current NavState's top volume
1150     if (top) {
1151       auto inside = currentLogical->GetUnplacedVolume()->Inside(localpoint);
1152       if (inside == kOutside) return nullptr;
1153       // Set the boundary state to the path
1154       if (inside == kSurface) path.SetBoundaryState(true);
1155     }
1156 
1157     Vector3D<Precision> currentpoint(localpoint);
1158     Vector3D<Precision> daughterlocalpoint;
1159     // exclude->id() returns unsigned int, but LevelInside takes a long as an input
1160     long exclude_id = exclude ? static_cast<long>(exclude->id()) : -1;
1161     long pvol_id    = -1;
1162 
1163     while (currentLogical->GetDaughters().size() > 0) {
1164       auto *bvh = GetBVH(currentLogical->id());
1165 
1166       const auto inside = LevelInside<Self_t>(*bvh, exclude_id, currentpoint, pvol_id, daughterlocalpoint);
1167 
1168       if (inside == kOutside) break; // no containing daughter here
1169       if (inside == kSurface) path.SetBoundaryState(true);
1170 
1171       auto *placed = GetPlacedVolume(pvol_id);
1172       path.Push(placed);
1173 
1174       // Prepare for next level: switch to daughter's logical volume + daughter-local point
1175       currentpoint   = daughterlocalpoint;
1176       currentLogical = placed->GetLogicalVolume();
1177 
1178       // Only exclude the placed volume once since we could enter it again via a
1179       // different volume history.
1180       exclude_id = -1;
1181       exclude    = nullptr;
1182     }
1183 
1184     return path.Top();
1185   }
1186 
1187   /** @} */
1188 
1189   // Computes a step in the current volume from the localpoint into localdir,
1190   // taking step_limit into account. If a volume is hit, the function calls
1191   // out_state.SetBoundaryState(true) and hitcandidate is set to the hit
1192   // daughter volume, or kept unchanged if the current volume is left.
1193   VECCORE_ATT_HOST_DEVICE
1194   static Precision ComputeStepAndHit(Vector3D<Precision> const &localpoint, Vector3D<Precision> const &localdir,
1195                                      Precision step_limit, vecgeom::NavigationState const &in_state,
1196                                      vecgeom::NavigationState &out_state, Daughter &hitcandidate)
1197   {
1198     in_state.CopyTo(&out_state);
1199     // Just return unchanged current state if the step limit is null or invalid
1200     if (step_limit <= 0) return 0.;
1201 
1202     Precision step = step_limit;
1203     Daughter pvol  = in_state.Top();
1204     // Daughter last_exited = in_state.GetLastExited();
1205     long hitcandidate_index = -1;
1206     long last_exited_id     = -1;
1207 
1208     // need to calc DistanceToOut first
1209     step = pvol->DistanceToOut(localpoint, localdir, step_limit);
1210     // This should never happen as DistanceToOut should never return infinity (TBC)
1211     if (step == vecgeom::kInfLength) step = 0.;
1212     // Most solids ignore step_limit
1213     step = Min(step, step_limit);
1214     // Boundary very close or already outside
1215     if (step < kTolerance) {
1216       step = Max(Precision(0.), step);
1217       // Even if the point is outside the volume, we have to set the boundary flag to force relocation
1218       out_state.SetBoundaryState(true);
1219       return step;
1220     }
1221 
1222     // Now distance to children
1223     if (pvol->GetDaughters().size() > 0) {
1224       auto bvh = GetBVH(pvol->GetLogicalVolume()->id());
1225 
1226       hitcandidate_index = -1;
1227       // id is an uint, however we use a long in order to be able to fit the full uint range, and -1 in case there is no
1228       // last exited volume in the navigation state.
1229       last_exited_id = -1;
1230       // if (last_exited != nullptr) last_exited_id = last_exited->id();
1231 
1232       CheckDaughterIntersections<Self_t>(*bvh, localpoint, localdir, step, last_exited_id, hitcandidate_index);
1233 
1234       if (hitcandidate_index >= 0) {
1235         // A child was hit within the step_limit
1236         step         = Max(Precision(0.), step);
1237         hitcandidate = pvol->GetLogicalVolume()->GetDaughters()[hitcandidate_index];
1238         out_state.SetBoundaryState(true);
1239         return step;
1240       }
1241     }
1242 
1243     // Is geometry further away than physics step?
1244     if (step >= step_limit) {
1245       // Then this is a phyics step and we don't need to do anything.
1246       out_state.SetBoundaryState(false);
1247       return step_limit;
1248     }
1249 
1250     // Otherwise it is a geometry step and we push the point to the boundary.
1251     out_state.SetBoundaryState(true);
1252     return step;
1253   }
1254 
1255   // Computes a step in the current volume from the localpoint into localdir,
1256   // until the next daughter bounding box, taking step_limit into account.
1257   VECCORE_ATT_HOST_DEVICE
1258   static Precision ApproachNextVolume(Vector3D<Precision> const &localpoint, Vector3D<Precision> const &localdir,
1259                                       Precision step_limit, vecgeom::NavigationState const &in_state)
1260   {
1261     Precision step = step_limit;
1262     Daughter pvol  = in_state.Top();
1263     // Daughter last_exited = in_state.GetLastExited();
1264 
1265     if (pvol->GetDaughters().size() > 0) {
1266       auto bvh = GetBVH(pvol->GetLogicalVolume()->id());
1267 
1268       // id is an uint, however we use a long in order to be able to fit the full uint range, and -1 in case there is no
1269       // last exited volume in the navigation state.
1270       long last_exited_id = -1;
1271       // if (last_exited != nullptr) last_exited_id = last_exited->id();
1272 
1273       ApproachNextDaughter<Self_t>(*bvh, localpoint, localdir, step, last_exited_id);
1274       // Make sure we don't "step" on next boundary
1275       step -= 10 * vecgeom::kTolerance;
1276     }
1277 
1278     if (step == vecgeom::kInfLength && step_limit > 0) return 0;
1279 
1280     // Is geometry further away than physics step?
1281     if (step > step_limit) {
1282       // Then this is a phyics step and we don't need to do anything.
1283       return step_limit;
1284     }
1285 
1286     if (step < 0) {
1287       step = 0;
1288     }
1289 
1290     return step;
1291   }
1292 
1293   /** @name Tracking implementation
1294    *  These bodies transform global queries and compose the internal traversal helpers.
1295    *  @{ */
1296 
1297   /**
1298    * @brief Compute isotropic Safety from a global point in the current state.
1299    * @param globalpoint Point in global coordinates.
1300    * @param state Current navigation state.
1301    * @param limit Accuracy limit; values above it may be conservative.
1302    * @return Safety to the nearest boundary, or infinity when @p state is outside.
1303    */
1304   VECCORE_ATT_HOST_DEVICE
1305   static Precision ComputeSafetyImpl(Vector3D<Precision> const &globalpoint, vecgeom::NavigationState const &state,
1306                                      Precision limit)
1307   {
1308     Daughter pvol = state.Top();
1309     if (pvol == nullptr) return kInfLength;
1310     vecgeom::Transformation3D m;
1311     state.TopMatrix(m);
1312     Vector3D<Precision> localpoint = m.Transform(globalpoint);
1313 
1314     // need to calc DistanceToOut first
1315     Precision safety = pvol->SafetyToOut(localpoint);
1316     limit            = Min(safety, limit);
1317 
1318     if (safety > 0 && pvol->GetDaughters().size() > 0) {
1319       auto bvh = GetBVH(pvol->GetLogicalVolume()->id());
1320       safety   = ComputeBVHSafety<Self_t>(*bvh, localpoint, safety, limit);
1321     }
1322 
1323     return safety;
1324   }
1325 
1326   /**
1327    * @brief Compute a bounded step and fully relocate the output state.
1328    * @param globalpoint Point in global coordinates and inside @p in_state.
1329    * @param globaldir Unit direction in global coordinates.
1330    * @param step_limit Maximum requested step.
1331    * @param in_state Current navigation state.
1332    * @param[out] out_state State at the endpoint, including transitive boundary relocation.
1333    * @return Geometry-limited or requested step length.
1334    */
1335   VECCORE_ATT_HOST_DEVICE
1336   static Precision ComputeStepAndPropagatedStateImpl(Vector3D<Precision> const &globalpoint,
1337                                                      Vector3D<Precision> const &globaldir, Precision step_limit,
1338                                                      vecgeom::NavigationState const &in_state,
1339                                                      vecgeom::NavigationState &out_state)
1340   {
1341     if (in_state.Top() == nullptr) return kInfLength;
1342     const Precision push = in_state.IsOnBoundary() ? kBoundaryPush : 0.;
1343 
1344     if (step_limit < push) {
1345       // Go as far as the step limit says, assuming there is no boundary.
1346       // TODO: Does this make sense?
1347       in_state.CopyTo(&out_state);
1348       out_state.SetBoundaryState(false);
1349       return step_limit;
1350     }
1351     step_limit -= push;
1352 
1353     // calculate local point/dir from global point/dir
1354     Vector3D<Precision> localpoint;
1355     Vector3D<Precision> localdir;
1356     // Impl::DoGlobalToLocalTransformation(in_state, globalpoint, globaldir, localpoint, localdir);
1357     vecgeom::Transformation3D m;
1358     in_state.TopMatrix(m);
1359     localpoint = m.Transform(globalpoint);
1360     localdir   = m.TransformDirection(globaldir);
1361 
1362     Daughter hitcandidate = nullptr;
1363     // Avoid computing the distance from boundary by pushing the point
1364     Precision step =
1365         ComputeStepAndHit(localpoint + push * localdir, localdir, step_limit, in_state, out_state, hitcandidate);
1366     step += push;
1367 
1368     if (out_state.IsOnBoundary()) {
1369       // Relocate the point after the step to refine out_state.
1370       localpoint += (step + kBoundaryPush) * localdir;
1371 
1372       if (!hitcandidate) {
1373         // We didn't hit a daughter but instead we're exiting the current volume.
1374         RelocatePoint(localpoint, out_state);
1375       } else {
1376         // Otherwise check if we're directly entering other daughters transitively.
1377         LocatePointIn(hitcandidate, localpoint, out_state, false);
1378       }
1379 
1380       if (out_state.Top() != nullptr) {
1381         while (out_state.Top()->IsAssembly() || out_state.HasSamePathAsOther(in_state)) {
1382           out_state.Pop();
1383         }
1384         VECGEOM_ASSERT(!out_state.Top()->GetLogicalVolume()->GetUnplacedVolume()->IsAssembly());
1385       }
1386     }
1387 
1388     return step;
1389   }
1390 
1391   /**
1392    * @brief Compute a bounded step and update the state to the first crossed boundary.
1393    *
1394    * The output state enters the hit daughter or leaves the current volume, but
1395    * does not resolve additional coincident boundaries. Call
1396    * `RelocateToNextVolume()` after moving the track to the returned endpoint.
1397    *
1398    * @param globalpoint Point in global coordinates and inside @p in_state.
1399    * @param globaldir Unit direction in global coordinates.
1400    * @param step_limit Maximum requested step.
1401    * @param in_state Current navigation state.
1402    * @param[out] out_state State at the first crossed boundary, or a copy of @p in_state for a physics step.
1403    * @return Geometry-limited or requested step length.
1404    */
1405   VECCORE_ATT_HOST_DEVICE
1406   static Precision ComputeStepAndNextVolumeImpl(Vector3D<Precision> const &globalpoint,
1407                                                 Vector3D<Precision> const &globaldir, Precision step_limit,
1408                                                 vecgeom::NavigationState const &in_state,
1409                                                 vecgeom::NavigationState &out_state)
1410   {
1411     if (in_state.Top() == nullptr) return kInfLength;
1412     const Precision push = in_state.IsOnBoundary() ? kBoundaryPush : 0.;
1413 
1414     if (step_limit < push) {
1415       // Go as far as the step limit says, assuming there is no boundary.
1416       // TODO: Does this make sense?
1417       in_state.CopyTo(&out_state);
1418       if (step_limit > kTolerance) out_state.SetBoundaryState(false);
1419       return step_limit;
1420     }
1421     step_limit -= push;
1422 
1423     // calculate local point/dir from global point/dir
1424     Vector3D<Precision> localpoint;
1425     Vector3D<Precision> localdir;
1426     // Impl::DoGlobalToLocalTransformation(in_state, globalpoint, globaldir, localpoint, localdir);
1427     vecgeom::Transformation3D m;
1428     in_state.TopMatrix(m);
1429     localpoint = m.Transform(globalpoint);
1430     localdir   = m.TransformDirection(globaldir);
1431 
1432     Daughter hitcandidate = nullptr;
1433     // Avoid computing the distance from boundary by pushing the point
1434     Precision step =
1435         ComputeStepAndHit(localpoint + push * localdir, localdir, step_limit, in_state, out_state, hitcandidate);
1436     step += (step > 0.) * push;
1437 
1438     if (out_state.IsOnBoundary()) {
1439       if (!hitcandidate) {
1440         vecgeom::VPlacedVolume const *currentmother = out_state.Top();
1441         Vector3D<Precision> transformed             = localpoint;
1442         // Push the point inside the next volume.
1443         transformed += (step + kBoundaryPush) * localdir;
1444         do {
1445           out_state.SetLastExited();
1446           out_state.Pop();
1447           transformed   = currentmother->GetTransformation()->InverseTransform(transformed);
1448           currentmother = out_state.Top();
1449         } while (currentmother &&
1450                  (currentmother->IsAssembly() || currentmother->GetUnplacedVolume()->Inside(transformed) != kInside));
1451       } else {
1452         out_state.Push(hitcandidate);
1453       }
1454     }
1455 
1456     return step;
1457   }
1458 
1459   /**
1460    * @brief Compute a bounded approach step without changing the navigation state.
1461    * @param globalpoint Point in global coordinates and inside @p in_state.
1462    * @param globaldir Unit direction in global coordinates.
1463    * @param step_limit Maximum requested step.
1464    * @param in_state Current navigation state.
1465    * @return Step limited by the next daughter approach or by @p step_limit.
1466    */
1467   VECCORE_ATT_HOST_DEVICE
1468   static Precision ComputeStepToApproachNextVolumeImpl(Vector3D<Precision> const &globalpoint,
1469                                                        Vector3D<Precision> const &globaldir, Precision step_limit,
1470                                                        vecgeom::NavigationState const &in_state)
1471   {
1472     if (in_state.Top() == nullptr) return kInfLength;
1473     // calculate local point/dir from global point/dir
1474     Vector3D<Precision> localpoint;
1475     Vector3D<Precision> localdir;
1476     // Impl::DoGlobalToLocalTransformation(in_state, globalpoint, globaldir, localpoint, localdir);
1477     vecgeom::Transformation3D m;
1478     in_state.TopMatrix(m);
1479     localpoint = m.Transform(globalpoint);
1480     localdir   = m.TransformDirection(globaldir);
1481 
1482     Precision step = ApproachNextVolume(localpoint, localdir, step_limit, in_state);
1483 
1484     return step;
1485   }
1486 
1487   /**
1488    * @brief Complete relocation after `ComputeStepAndNextVolume()`.
1489    * @param globalpoint Track endpoint in global coordinates.
1490    * @param globaldir Track direction in global coordinates.
1491    * @param[in,out] state Boundary state to descend through coincident volumes.
1492    */
1493   VECCORE_ATT_HOST_DEVICE
1494   static void RelocateToNextVolumeImpl(Vector3D<Precision> const &globalpoint, Vector3D<Precision> const &globaldir,
1495                                        vecgeom::NavigationState &state)
1496   {
1497     // if already outside, don't do anything
1498     if (state.IsOutside()) return;
1499 
1500     // Push the point inside the next volume.
1501     // A.G. This should not be needed now since LocatePointIn is boundary-aware
1502     Vector3D<Precision> pushed = globalpoint /* + kBoundaryPush * globaldir*/;
1503 
1504     // Calculate local point from global point.
1505     vecgeom::Transformation3D m;
1506     state.TopMatrix(m);
1507     Vector3D<Precision> localpoint = m.Transform(pushed);
1508 
1509     // passing the state to check in + the local point in the reference frame of the state
1510     LocatePointInNavState(localpoint, state, false, state.GetLastExited());
1511 
1512     if (state.Top() != nullptr) {
1513       while (state.Top()->IsAssembly()) {
1514         state.Pop();
1515       }
1516       VECGEOM_ASSERT(!state.Top()->GetLogicalVolume()->GetUnplacedVolume()->IsAssembly());
1517     }
1518   }
1519 
1520   /** @} */
1521 };
1522 
1523 /// Explicit name for the navigator backed by IndexedBVH.
1524 using IndexedBVHNavigator = BVHNavigator;
1525 
1526 } // namespace vecgeom
1527 
1528 #endif // BVH_NAVIGATOR_H