Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-21 10:32:26

0001 /*
0002  * \file GenTrapImplementation.h
0003  * \brief Navigation kernels for the Generic Trapezoid (Arb8).
0004  *
0005  * This header implements the runtime kernels (Contains/Inside, Distance, Safety, Normal)
0006  * that operate on the immutable data stored in GenTrapStruct (see GenTrapStruct.h).
0007  *
0008  * Performance notes:
0009  *  - Planar cases can be short-circuited via TessellatedSection.
0010  *  - Lateral twisted faces (bilinear patches) use a cheap v(z)-window
0011  *    to cull impossible distance ranges before doing any quadratic/UV work.
0012  *  - For ray/face intersection we adopt a half-open step window [lmin, lmax),
0013  *    so hits at exactly lmax are considered "not in range" and lmin is inclusive
0014  *    up to a small negative tolerance to absorb FP noise.
0015  *
0016  *  Created on: Aug 2, 2014
0017  *      Author: swenzel
0018  *   Review/completion: Nov 4, 2015
0019  *      Author: mgheata
0020  *  Full scalar refactoring: andrei.gheata@cern.ch
0021  */
0022 
0023 #ifndef VECGEOM_VOLUMES_KERNEL_GENTRAPIMPLEMENTATION_H_
0024 #define VECGEOM_VOLUMES_KERNEL_GENTRAPIMPLEMENTATION_H_
0025 
0026 #include "VecGeom/base/Global.h"
0027 #include "VecGeom/base/Vector2D.h"
0028 
0029 #include "VecGeom/volumes/kernel/GenericKernels.h"
0030 #include "VecGeom/volumes/kernel/BoxImplementation.h"
0031 #include "VecGeom/volumes/SurfaceHitView.h"
0032 #include "VecGeom/volumes/UnplacedGenTrap.h"
0033 
0034 #include <iostream>
0035 
0036 namespace vecgeom {
0037 
0038 VECGEOM_DEVICE_FORWARD_DECLARE(struct GenTrapImplementation;);
0039 VECGEOM_DEVICE_DECLARE_CONV(struct, GenTrapImplementation);
0040 
0041 inline namespace VECGEOM_IMPL_NAMESPACE {
0042 
0043 class PlacedGenTrap;
0044 class UnplacedGenTrap;
0045 
0046 template <typename T>
0047 struct GenTrapStruct;
0048 
0049 struct GenTrapImplementation {
0050 
0051   using Vertex_t         = Vector3D<Precision>;
0052   using PlacedShape_t    = PlacedGenTrap;
0053   using UnplacedStruct_t = GenTrapStruct<Precision>;
0054   using UnplacedVolume_t = UnplacedGenTrap;
0055 
0056   /// Boundary selected by the existing DistanceToOut minimization.
0057   enum class ExitSurface : signed char { kNone = -1, kZMin, kZMax, kLateral0, kLateral1, kLateral2, kLateral3 };
0058 
0059   /**
0060    * \brief Point containment test (fast path, no surface classification).
0061    *
0062    * Checks whether a point lies inside the generalized trapezoid volume.
0063    * This is typically cheaper than Inside() as it does not distinguish
0064    * between kInside and kSurface -- it only returns a boolean.
0065    *
0066    * \tparam Real_v   Scalar floating type
0067    * \param unplaced  Geometry data structure of the GenTrap
0068    * \param point     Query point in local coordinates
0069    * \param[out] inside  True if the point is not rejected by any face
0070    */
0071   template <typename Real_v>
0072   VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void Contains(UnplacedStruct_t const &unplaced,
0073                                                                     Vector3D<Real_v> const &point, bool &inside);
0074 
0075   /**
0076    * \brief Classify a point with respect to the solid.
0077    *
0078    * Returns one of EInside::{kInside, kSurface, kOutside}. This may perform
0079    * additional tolerance checks vs. Contains().
0080    *
0081    * \tparam Real_v     Scalar or SIMD floating type
0082    * \param unplaced    Geometry data structure of the GenTrap
0083    * \param point       Query point in local coordinates
0084    * \param[out] inside Classification result
0085    */
0086   template <typename Real_v>
0087   VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void Inside(UnplacedStruct_t const &unplaced,
0088                                                                   Vector3D<Real_v> const &point, Inside_t &inside);
0089 
0090   /**
0091    * \brief Shared kernel used by Contains() and Inside().
0092    *
0093    * Evaluates the bilinear/planar surface equations on the four lateral faces
0094    * (and the implicit Z slabs) to determine quick-reject/accept masks.
0095    * When ForInside=true, it additionally computes a conservative
0096    * \c completelyinside mask.
0097    *
0098    * \tparam Real_v   Scalar type (assumed scalar in this implementation)
0099    * \tparam ForInside If true, also compute \c completelyinside; otherwise only outside mask
0100    * \param unplaced   Geometry data structure of the GenTrap
0101    * \param point      Query point
0102    * \param[out] completelyinside True if strictly inside all faces by tolerance
0103    * \param[out] completelyoutside True if outside any face by tolerance
0104    */
0105   template <typename Real_v, bool ForInside>
0106   VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void GenericKernelForContainsAndInside(
0107       UnplacedStruct_t const &unplaced, Vector3D<Real_v> const &point, bool &completelyinside, bool &completelyoutside);
0108 
0109   /**
0110    * \brief Ray entry distance from an external point.
0111    *
0112    * Computes the distance along \p direction from \p point to enter the solid,
0113    * honoring \p stepMax. Returns \c -1 for points that are already inside.
0114    *
0115    * \tparam Real_v Scalar or SIMD floating type
0116    * \param unplaced Geometry data structure of the GenTrap
0117    * \param point    Start point (expected outside)
0118    * \param direction Normalized or non-normalized direction; sign matters
0119    * \param stepMax  Upper bound for the step; intersections beyond are ignored
0120    * \param[out] distance The entry distance, or +inf if no hit, or -1 if already inside
0121    */
0122   template <typename Real_v>
0123   VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void DistanceToIn(UnplacedStruct_t const &unplaced,
0124                                                                         Vector3D<Real_v> const &point,
0125                                                                         Vector3D<Real_v> const &direction,
0126                                                                         Real_v const &stepMax, Real_v &distance);
0127 
0128   /**
0129    * \brief Ray exit distance with optional supporting-normal output.
0130    *
0131    * Computes the distance from \p point along \p direction to leave the solid.
0132    *
0133    * Caps and planar lateral faces support the whole solid. Twisted lateral
0134    * exits conservatively leave hitInfo->fLeftBehind false but supply the normal.
0135    * A null hitInfo retains the ordinary distance-only path.
0136    *
0137    * \tparam Real_v Scalar floating-point type
0138    * \param unplaced Geometry data structure of the GenTrap
0139    * \param point Start point inside or on the surface
0140    * \param direction Unit ray direction
0141    * \param stepMax  Currently unused upper bound (kept for API symmetry)
0142    * \param[out] distance Exit distance; tolerated surface starts may yield a
0143    * small negative value. Outside starts return -1, or -kTolerance in the planar helper.
0144    * \param[out] hitInfo Optional output; cleared first, with a unit normal
0145    * written only when requested and the selected boundary supports the solid
0146    */
0147   template <typename Real_v>
0148   VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void DistanceToOut(UnplacedStruct_t const &unplaced,
0149                                                                          Vector3D<Real_v> const &point,
0150                                                                          Vector3D<Real_v> const &direction,
0151                                                                          Real_v const &stepMax, Real_v &distance,
0152                                                                          SurfaceHitView<Real_v> *hitInfo = nullptr);
0153 
0154   /** @brief Compute the exit distance with compile-time optional winner recording. */
0155   template <typename Real_v, bool RecordHitInfo>
0156   VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void DistanceToOutImpl(UnplacedStruct_t const &unplaced,
0157                                                                              Vector3D<Real_v> const &point,
0158                                                                              Vector3D<Real_v> const &direction,
0159                                                                              Real_v const &stepMax, Real_v &distance,
0160                                                                              SurfaceHitView<Real_v> *hitInfo);
0161 
0162   /** @brief Convert a selected cap or lateral face into exit-normal output; twisted faces use the normal at the hit. */
0163   template <typename Real_v>
0164   VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void SetExitHit(UnplacedStruct_t const &unplaced,
0165                                                                       ExitSurface surface,
0166                                                                       Vector3D<Real_v> const &hitPoint,
0167                                                                       SurfaceHitView<Real_v> *hitInfo);
0168 
0169   /**
0170    * \brief Conservative safety from outside to the solid.
0171    *
0172    * Returns an underestimate of the distance one must travel to reach the surface
0173    * from \p point. If \p point is outside the bounding box, the box safety is used.
0174    *
0175    * \tparam Real_v Scalar type (assumed scalar here)
0176    * \param unplaced Geometry data structure of the GenTrap
0177    * \param point    Query point
0178    * \param[out] safety Non-negative lower bound to the closest surface
0179    */
0180   template <typename Real_v>
0181   VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void SafetyToIn(UnplacedStruct_t const &unplaced,
0182                                                                       Vector3D<Real_v> const &point, Real_v &safety);
0183 
0184   /**
0185    * \brief Conservative safety from inside to the exterior.
0186    *
0187    * Returns an underestimate to the nearest exit surface.
0188    * If the point is found outside along Z, returns -1.
0189    *
0190    * \tparam Real_v Scalar type (assumed scalar here)
0191    * \param unplaced Geometry data structure of the GenTrap
0192    * \param point    Query point
0193    * \param[out] safety Lower bound to the nearest exit; -1 if already outside on Z
0194    */
0195   template <typename Real_v>
0196   VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void SafetyToOut(UnplacedStruct_t const &unplaced,
0197                                                                        Vector3D<Real_v> const &point, Real_v &safety);
0198 
0199   /**
0200    * \brief Compute a unit-length outward normal at a surface point.
0201    *
0202    * Caps take precedence within tolerance; otherwise incident lateral normals
0203    * are averaged. Unmatched points use the nearest-edge approximation, with
0204    * twisted-face validity determined by tolerance-extended patch coordinates.
0205    *
0206    * \tparam Real_v Scalar type (assumed scalar here)
0207    * \param unplaced Geometry data structure of the GenTrap
0208    * \param point    Point on (or near) a surface
0209    * \param[out] normal Unit outward normal (undefined if !valid)
0210    * \param[out] valid  True if a consistent normal could be determined
0211    */
0212   template <typename Real_v>
0213   VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void NormalKernel(UnplacedStruct_t const &unplaced,
0214                                                                         Vector3D<Real_v> const &point,
0215                                                                         Vector3D<Real_v> &normal, bool &valid);
0216 
0217   /// Utility functions
0218 
0219   /**
0220    * \brief Distance computation to a lateral surface.
0221    *
0222    * Handles both planar and twisted bilinear faces. For planar faces it reduces
0223    * to a plane intersection followed by in-range checks; for twisted faces it
0224    * solves a quadratic derived from the bilinear patch intersection.
0225    *
0226    * \tparam Real_v Precision type
0227    * \param unplaced Geometry data structure of the GenTrap
0228    * \param point Point
0229    * \param dir Direction (need not be unit length)
0230    * \param i Surface index [0,3]
0231    * \param in Inside state of the point (true if the ray starts inside)
0232    * \param lmin Minimum distance limit used to early-reject intersections
0233    * \param lmax Maximum distance limit used to early-reject intersections
0234    * \param assumeInsideStart True when the caller guarantees an inside/surface exit start
0235    * \return Distance to surface (\c +inf if no accepted hit lies in the window)
0236    */
0237   template <typename Real_v>
0238   VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static Real_v DistanceToSurf(
0239       UnplacedStruct_t const &unplaced, Vector3D<Real_v> const &point, Vector3D<Real_v> const &dir, int i, bool in,
0240       Real_v lmin = Real_v(0), Real_v lmax = InfinityLength<Real_v>(), bool assumeInsideStart = false);
0241 
0242   /** \brief Fill vertices of the section at a given Z.
0243    *
0244    * \tparam Real_v Precision type
0245    * \param unplaced Geometry data structure of the GenTrap
0246    * \param z Z coordinate at which to evaluate the section
0247    * \param[out] vertices Out-parameter with the 4 XY vertices of the section
0248    */
0249   template <typename Real_v>
0250   VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void FillVerticesAtZ(UnplacedStruct_t const &unplaced, Real_v z,
0251                                                                            Vector2D<Real_v> vertices[4]);
0252 
0253   /**
0254    * \brief Return the index of the edge closest to a given point (projected in XY).
0255    *
0256    * \tparam Real_v Scalar type
0257    * \param point   Query point (only x,y used)
0258    * \param vertxy  The four section vertices in XY
0259    * \param[out] iseg Index of the closest edge in [0,3]
0260    */
0261   template <class Real_v>
0262   VECCORE_ATT_HOST_DEVICE static void GetClosestEdge(Vector3D<Real_v> const &point, Vector2D<Real_v> const vertxy[4],
0263                                                      int &iseg);
0264 
0265   /** \brief Point-in-quad test on a Z section.
0266    *
0267    * Evaluates if the XY of \p point lies inside the quadrilateral defined by
0268    * \p v on the plane z=const of the corresponding section.
0269    *
0270    * \tparam Real_v Scalar type
0271    * \param point Query point (z is ignored except for consistency)
0272    * \param v     The four vertices of the section at the same z
0273    * \return True if inside (within tolerance); false if degenerate or outside
0274    */
0275   template <typename Real_v>
0276   VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static bool InsideSection(Vector3D<Real_v> const &point,
0277                                                                          Vector3D<Real_v> const v[4]);
0278 
0279   /**
0280    * \brief Check whether a point on lateral surface \p isurf is within its parametric bounds.
0281    *
0282    * Uses the inverse mapping (XYZ->(u,v)) and tests 0<=u,v<=1 with tolerance.
0283    *
0284    * \tparam Real_v Scalar type
0285    * \param unplaced Geometry data
0286    * \param point    Point assumed on the surface
0287    * \param isurf    Surface index [0,3]
0288    * \return True if the (u,v) parameters lie within [0,1]^2 (with tolerance)
0289    */
0290   template <typename Real_v>
0291   VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static bool InSurfLimits(UnplacedStruct_t const &unplaced,
0292                                                                         Vector3D<Real_v> const &point, int isurf);
0293 
0294   /**
0295    * \brief Safety helper across the four lateral faces.
0296    *
0297    * Computes a conservative signed safety by aggregating the maximum of
0298    * signed distances (planar faces) or Lipschitz-continuous bounds (twisted faces).
0299    *
0300    * \tparam Real_v Scalar type
0301    * \param unplaced Geometry data
0302    * \param point    Query point
0303    * \param safmax   Initial safety bound (typically Z safety)
0304    * \param inside   If true, returns negative safety; otherwise positive
0305    * \return Signed conservative safety
0306    */
0307   template <typename Real_v>
0308   VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static Real_v SafetyArb4(UnplacedStruct_t const &unplaced,
0309                                                                         Vector3D<Real_v> const &point, Real_v safmax,
0310                                                                         bool inside = true);
0311 
0312   /**
0313    * \brief Normal vector to a bilinear surface (un-normalized).
0314    *
0315    * The surface is parameterized as:
0316    * \f[
0317    * P(u,v) = (1-u)(1-v)P_1 + u(1-v)P_2 + (1-u)vP_3 + uvP_4
0318    * \f]
0319    * whose (non-normalized) normal is \f\vec n = \partial_u P \times \partial_v P\f.
0320    * The user may validate containment in the surface patch if (u,v) parameters lie within [0,1]^2 (with tolerance)
0321    *
0322    * \tparam Real_v Scalar type
0323    * \param unplaced Geometry data
0324    * \param point Point assumed on surface i
0325    * \param i Index of the lateral surface [0,3]
0326    * \param[out] unorm Un-normalized outward normal
0327    * \param[out] u shear coordinate at point.z()
0328    * \param[out] v generator coordinate
0329    */
0330   template <typename Real_v>
0331   VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE static void UNormal(UnplacedStruct_t const &unplaced,
0332                                                                    Vector3D<Real_v> const &point, int i,
0333                                                                    Vector3D<Real_v> &unorm, Real_v &u, Real_v &v);
0334 
0335   /** \brief Inverse mapping from cartesian point on a lateral face to (u,v).
0336    *
0337    * Implements the inverse of the bilinear patch equation restricted to the
0338    * generator pair (A,C) and (B,D) bounding the face.
0339    *
0340    * \tparam Real_v Scalar type
0341    * \param unplaced Geometry data
0342    * \param point Point in cartesian space, assumed on the bilinear surface i
0343    * \param i Index of the surface the point is on in the range [0, 3]
0344    * \return (u,v) coordinates within [0,1]^2 if the point is on the face
0345    */
0346   template <typename Real_v>
0347   VECCORE_ATT_HOST_DEVICE static Vector2D<Real_v> XYZtoUV(UnplacedStruct_t const &unplaced,
0348                                                           Vector3D<Real_v> const &point, int i);
0349 }; // End struct GenTrapImplementation
0350 
0351 //********************************
0352 //**** implementations start here
0353 //********************************/
0354 
0355 //______________________________________________________________________________
0356 // --- Cheap, safe interval culls for twisted faces ---
0357 /**
0358  * \brief Compute the admissible t-interval such that the parametric v(t) stays in [0,1].
0359  *
0360  * The bilinear patch is parameterized with v determined by z:
0361  * \f[
0362  *   v(t) = \frac{z(t) + D_z}{2 D_z} = \frac{p_z + t\,d_z + D_z}{2 D_z}.
0363  * \f]
0364  * We pass \p Dz2 = 1/(2*D_z) to avoid divides. The result interval is intersected
0365  * with the user-provided forward limit \p limit and returned as [tmin,tmax].
0366  *
0367  * \param ptZ   start point z
0368  * \param dirZ  ray z-component
0369  * \param Dz2   precomputed 1/(2*Dz)
0370  * \param limit upper bound on t from the caller (e.g. stepMax)
0371  * \param[out] tmin lower bound of the feasible window
0372  * \param[out] tmax upper bound of the feasible window
0373  * \return false if the feasible window is empty
0374  */
0375 template <typename Real_v>
0376 VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE bool GenTrap_VInterval(Real_v ptZ, Real_v dirZ, Real_v Dz2, Real_v limit,
0377                                                                     Real_v &tmin, Real_v &tmax)
0378 {
0379   // v(t) = (ptZ + Dz + dirZ*t) / (2*Dz) must stay in [0,1]
0380   const Real_v kv = dirZ * Dz2;              // slope of v(t)
0381   const Real_v v0 = ptZ * Dz2 + Real_v(0.5); // v at t=0
0382   Real_v t0 = Real_v(0), t1 = limit;         // user range
0383   if (Abs(kv) < kToleranceDist<Real_v>) {
0384     // v is (almost) constant along the ray
0385     if (v0 < Real_v(0) - kToleranceDist<Real_v> || v0 > Real_v(1) + kToleranceDist<Real_v>) return false;
0386     tmin = t0;
0387     tmax = t1;
0388     return true;
0389   }
0390   const Real_v t_at_0 = (Real_v(0) - v0) / kv;
0391   const Real_v t_at_1 = (Real_v(1) - v0) / kv;
0392   Real_v a = Min(t_at_0, t_at_1), b = Max(t_at_0, t_at_1);
0393   t0 = Max(t0, a);
0394   t1 = Min(t1, b);
0395   if (t1 < t0) return false;
0396   tmin = t0;
0397   tmax = t1;
0398   return true;
0399 }
0400 
0401 //______________________________________________________________________________
0402 template <typename Real_v>
0403 VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE Real_v GenTrapImplementation::DistanceToSurf(
0404     UnplacedStruct_t const &unplaced, Vector3D<Real_v> const &point, Vector3D<Real_v> const &dir, int i, bool in,
0405     Real_v lmin, Real_v lmax, bool assumeInsideStart)
0406 {
0407   // Return a large sentinel for "no hit"
0408   Real_v big = InfinityLength<Real_v>();
0409   VECGEOM_ASSERT(!unplaced.IsDegenerated(i) && "DistanceToSurf called with degenerated face");
0410 
0411   // NOTE on window semantics:
0412   //   * We use a half-open window [lmin, lmax) to keep composition simple when
0413   //     iterating faces; a hit exactly at lmax is considered "out of range".
0414   //   * We allow a tiny negative slack at lmin to absorb FP error when starting
0415   //     very close to a surface: (t < lmin - tol) is rejected.
0416   //   * For inside->out queries, the first positive root is a valid exit
0417   //     as soon as it passes the window tests, hence early-return is safe.
0418 
0419   if (!unplaced.IsTwisted(i)) {
0420     // -------------------------
0421     // Planar face intersection
0422     // -------------------------
0423 
0424     // Signed plane safety: <0 means inside, >0 outside w.r.t. stored outward normal
0425     const Real_v safety = unplaced.fSurf[i].EvaluatePlanar(point); // n.p + g
0426     const Real_v dn     = unplaced.fSurf[i].DotPlaneNormal(dir);
0427 
0428     // Reject points on the wrong side or going in the wrong direction.
0429     //  - side_ok   : start is consistent with inside/outside state (tolerant)
0430     //  - facing_ok : direction crosses the plane in the correct sense
0431     // An exit must face outward: an inward near-parallel ray can have a large
0432     // backward root even from strictly inside, which must not be clamped to zero.
0433     const bool facing_ok = in ? dn > Real_v(0.) : dn < -kToleranceDist<Real_v>;
0434     const bool side_ok   = (in && safety < Real_v(kTolerance)) || (!in && safety > Real_v(-kTolerance));
0435     if (!facing_ok || !side_ok) return big;
0436 
0437     // Clamp tolerated backward crossings before the window check, so a surface
0438     // start is not discarded merely because its plane root lies behind it.
0439     Real_v snext = Max(-safety / NonZero(dn), Real_v(0.));
0440     // window culls before UV work
0441     if ((snext < lmin - kToleranceDist<Real_v>) || (snext >= lmax)) return big;
0442 
0443     // From strictly inside, the minimum over all faces and caps selects the
0444     // finite patch; an individual plane candidate need not recover its bounds.
0445     if (assumeInsideStart && safety < Real_v(-kTolerance)) return snext;
0446 
0447     // Validate the hit point lies within the finite bilinear bounds of the face
0448     return InSurfLimits<Real_v>(unplaced, point + snext * dir, i) ? snext : big;
0449   } else {
0450     // ---------------------------
0451     // Twisted bilinear intersection
0452     // ---------------------------
0453     // Intersection reduces to a quadratic in t; we test candidate roots against
0454     // the [lmin,lmax) window first, then validate against patch (u,v) bounds.
0455     // The code below uses directly the surface equation, but it is slower:
0456     // Real_v a, b, c;
0457     // unplaced.fSurf[i].RayQuadratic(point, dir, a, b, c);
0458 
0459 #if GENTRAP_USE_HYBRID_COEFFS
0460     const auto pointXY = point.XY();
0461     const auto dirXY   = dir.XY();
0462     const auto z       = point[2];
0463     const auto dz      = dir[2];
0464 
0465     // Cached per-face differences
0466     const auto &dMid = unplaced.fDmid[i];
0467     const auto &dT   = unplaced.fDT[i];
0468 
0469     // Cached scalars (tiny memory footprint)
0470     const Real_v TT = unplaced.fTT[i];
0471     const Real_v MM = unplaced.fMM[i];
0472     const Real_v MT = unplaced.fMT[i];
0473 
0474     // Helper: z-component of 2D cross (kept inlined by the compiler)
0475     auto xz = [](auto const &a, auto const &b) -> Real_v { return a.x() * b.y() - a.y() * b.x(); };
0476 
0477     // Quadratic coefficients (hybrid precompute form)
0478     const Real_v dT_x_dir   = xz(dT, dirXY);
0479     const Real_v dT_x_point = xz(dT, pointXY);
0480     const Real_v dMid_x_dir = xz(dMid, dirXY);
0481     const Real_v dMid_x_pt  = xz(dMid, pointXY);
0482 
0483     // Share point-dependent terms in the quadratic's Horner form.
0484     const Real_v zTT        = z * TT;
0485     const Real_v pointTerms = dT_x_point + MT + zTT;
0486     Real_v a                = dz * (dT_x_dir + TT * dz);
0487     Real_v b                = dMid_x_dir + z * dT_x_dir + (pointTerms + zTT) * dz;
0488     Real_v c                = dMid_x_pt + MM + z * pointTerms;
0489 #else
0490     int j = (i + 1) % 4;
0491 
0492     // Unpack a few frequently used quantities
0493     auto const pointXY = point.XY();  // project to XY
0494     auto const dirXY   = dir.XY();    // project direction to XY
0495     auto const t       = unplaced.fT; // shear vectors per vertex
0496 
0497     auto const s1 = unplaced.fMidXY[i] + t[i] * point[2]; // generator at z
0498     auto const s2 = unplaced.fMidXY[j] + t[j] * point[2];
0499     auto ds       = s2 - s1;
0500 
0501     // Quadratic coefficients (original on-the-fly derivation)
0502     Real_v a = ((t[j] - t[i]).CrossZ(dirXY) + t[i].CrossZ(t[j]) * dir[2]) * dir[2];
0503     Real_v b = ds.CrossZ(dirXY) + ((t[j] - t[i]).CrossZ(pointXY) + s1.CrossZ(t[j]) - s2.CrossZ(t[i])) * dir[2];
0504     Real_v c = ds.CrossZ(pointXY) + s1.CrossZ(s2);
0505 #endif
0506 
0507     constexpr Real_v tolerance = kToleranceArb4<Real_v>;
0508     if (assumeInsideStart) {
0509       // For regular interior starts the first forward zero is this face's exit
0510       // candidate. Starts in the tolerated surface band additionally select an
0511       // outward crossing, so an inward ray skips its root at zero.
0512       const bool regularInterior = c < -tolerance;
0513       if (a == Real_v(0.)) {
0514         if (b == Real_v(0.)) return big;
0515         const Real_v root = -c / b;
0516         if (!regularInterior && b <= Real_v(0.)) return big;
0517         if (root < lmin - tolerance || root >= lmax) return big;
0518         const Real_v candidate = Max(root, Real_v(0.));
0519         return regularInterior || InSurfLimits(unplaced, point + candidate * dir, i) ? candidate : big;
0520       }
0521 
0522       const Real_v halfB = Real_v(0.5) * b;
0523       const Real_v delta = halfB * halfB - a * c;
0524       if (delta < Real_v(0.)) return big;
0525       const Real_v q = -halfB - CopySign(Sqrt(delta), halfB);
0526       if (regularInterior && delta > Real_v(0.) && lmin == Real_v(0.)) {
0527         // Negative q gives the first forward root c/q; otherwise q/a is
0528         // the only possible forward root. Keep repeated roots and shifted
0529         // windows on the general path below.
0530         const bool smallRoot = q < Real_v(0.);
0531         const Real_v root    = (smallRoot ? c : q) / (smallRoot ? NonZero(q) : a);
0532         return root >= Real_v(0.) && root < lmax ? root : big;
0533       }
0534       const Real_v r1       = q / a;
0535       const Real_v r2       = c / NonZero(q);
0536       Real_v root           = InfinityLength<Real_v>();
0537       const bool r1InWindow = r1 >= lmin || (r1 >= lmin - tolerance && b > Real_v(0.));
0538       const bool r2InWindow = r2 >= lmin || (r2 >= lmin - tolerance && b > Real_v(0.));
0539       if (r1InWindow && (regularInterior || Real_v(2.) * a * r1 + b > Real_v(0.))) root = r1;
0540       if (r2InWindow && (regularInterior || Real_v(2.) * a * r2 + b > Real_v(0.))) root = Min(root, r2);
0541       if (root >= lmax) return big;
0542       const Real_v candidate = Max(root, Real_v(0.));
0543       return regularInterior || InSurfLimits(unplaced, point + candidate * dir, i) ? candidate : big;
0544     }
0545 
0546     auto acceptExteriorRoot = [&](Real_v root, Real_v derivative) {
0547       if (derivative >= Real_v(0.) || root < lmin - kToleranceDist<Real_v> || root >= lmax) return big;
0548       const Real_v candidate       = Max(root, Real_v(0.));
0549       constexpr Real_v uvTolerance = Real_v(8.) * kEpsilonT<Real_v>;
0550       const auto uv                = XYZtoUV(unplaced, point + candidate * dir, i);
0551       return (uv[0] > -uvTolerance) && (uv[0] < Real_v(1.) + uvTolerance) && (uv[1] > -uvTolerance) &&
0552                      (uv[1] < Real_v(1.) + uvTolerance)
0553                  ? candidate
0554                  : big;
0555     };
0556 
0557     if (!in && a == Real_v(0.)) {
0558       if (b >= Real_v(0.)) return big;
0559       return acceptExteriorRoot(-c / b, b);
0560     }
0561 
0562     Real_v dist[2] = {-InfinityLength<Real_v>(), -InfinityLength<Real_v>()};
0563     auto nroots    = QuadraticSolver(a, b, c, dist);
0564 
0565     // The solver counts roots using the tighter generic tolerance but preserves
0566     // both. Recover a discarded root within the twisted-surface band only for
0567     // a non-grazing crossing of this finite face in the requested sense.
0568     const Real_v discardedRoot = nroots < 2 ? dist[1 - nroots] : -InfinityLength<Real_v>();
0569     if (discardedRoot > -tolerance && InSurfLimits<Real_v>(unplaced, point, i)) {
0570       const auto grad         = unplaced.fSurf[i].EvaluateGradient(point);
0571       const Real_v projection = dir.Dot(grad);
0572       const bool nonGrazing   = projection * projection > kToleranceSquared * grad.Mag2();
0573       if (nonGrazing && (in ^ (projection < Real_v(0.)))) {
0574         // An edge start entering within the band must not leave a planar
0575         // lateral, which supports the whole solid.
0576         if (!in) {
0577           for (auto k = 0; k < 4; ++k) {
0578             if (unplaced.IsDegenerated(k) || unplaced.IsTwisted(k)) continue;
0579             if (unplaced.fSurf[k].EvaluatePlanar(point) > Real_v(-kTolerance) &&
0580                 unplaced.fSurf[k].DotPlaneNormal(dir) > kToleranceDist<Real_v>)
0581               return big;
0582           }
0583         }
0584         return Real_v(0.);
0585       }
0586     }
0587 
0588     // Prevent grazing rays when starting outside: two roots at ~0 within tolerance.
0589     if (!in && nroots == 2 && Abs(dist[0]) < tolerance && Abs(dist[1]) < tolerance) return big;
0590 
0591     // The inward crossing is the smaller root for an upward-opening
0592     // parabola and the larger root for a downward-opening one. Selecting it
0593     // directly avoids testing both roots and computing a three-component
0594     // implicit gradient for regular exterior entries.
0595     if (!in) {
0596       if (nroots == 0) return big;
0597       const Real_v root = a > Real_v(0.) ? dist[0] : dist[1];
0598       return acceptExteriorRoot(root, Real_v(2.) * a * root + b);
0599     }
0600 
0601     for (auto k = 2 - nroots; k < 2; ++k) {
0602       const Real_v troot = dist[k];
0603 
0604       // step window culls before UV/normal work
0605       if ((troot < lmin - kToleranceDist<Real_v>) || (troot >= lmax)) continue;
0606 
0607       // If the point is inside and not starting from a boundary, this is a minimization problem
0608       if (in && troot > tolerance) return troot; // inside: early minimum positive root is the exit
0609 
0610       // Allow roundoff at finite-patch edges, not a geometric tolerance in
0611       // dimensionless UV: the latter can admit remote hits on long faces.
0612       constexpr Real_v uvTolerance = Real_v(8.) * kEpsilonT<Real_v>;
0613       auto hit                     = point + troot * dir;
0614       auto uv                      = XYZtoUV(unplaced, hit, i);
0615       auto u                       = uv[0];
0616       auto v                       = uv[1];
0617       bool in_patch =
0618           (u > -uvTolerance) && (u < Real_v(1.) + uvTolerance) && (v > -uvTolerance) && (v < Real_v(1.) + uvTolerance);
0619       if (!in_patch) continue;
0620       // Crossing sense from the quadratic's slope, as for exterior roots, so
0621       // a tangent root cannot be both an entry and an exit.
0622       bool crosses_ok = in ^ (Real_v(2.) * a * troot + b < Real_v(0.));
0623       if (crosses_ok) return troot;
0624     }
0625   }
0626   return big;
0627 }
0628 
0629 //______________________________________________________________________________
0630 template <typename Real_v, bool ForInside>
0631 VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE void GenTrapImplementation::GenericKernelForContainsAndInside(
0632     UnplacedStruct_t const &unplaced, Vector3D<Real_v> const &point, bool &completelyinside, bool &completelyoutside)
0633 {
0634   // First stage: AABB quick reject/accept; second stage: evaluate lateral faces.
0635   // For ForInside=true we also compute a strict "completelyinside" mask
0636   // by testing f_i(point) < -tolerance for all active faces. Points within
0637   // tolerance of the Z slabs are treated specially so we do not incorrectly
0638   // classify them as strictly inside (we then return kSurface in Inside()).
0639 
0640   // Quick reject/accept using the axis-aligned bounding box (AABB)
0641   Vector3D<Real_v> halfsize(unplaced.fBBdimensions[0], unplaced.fBBdimensions[1], unplaced.fBBdimensions[2]);
0642   BoxImplementation::GenericKernelForContainsAndInside<Real_v, true>(halfsize, point - unplaced.fBBorigin,
0643                                                                      completelyinside, completelyoutside);
0644 
0645   constexpr Real_v tolerance = kToleranceArb4<Real_v>;
0646   if (completelyoutside) return; // outside the AABB => outside the solid
0647 
0648   // If the point lies on the top/bottom faces within tolerance, skip tightening of the inside mask
0649   auto on_surfz = (unplaced.fDz - Abs(point.z())) < Real_v(kTolerance);
0650 
0651   // Evaluate implicit equations for lateral faces; any positive value means "outside that face"
0652   VECGEOM_PRAGMA_UNROLL(4)
0653   for (int i = 0; i < 4; i++) {
0654     if (unplaced.IsDegenerated(i)) continue;
0655     auto eqeval = unplaced.IsTwisted(i) ? unplaced.fSurf[i].Evaluate(point) : unplaced.fSurf[i].EvaluatePlanar(point);
0656     completelyoutside = eqeval > tolerance;
0657     if (completelyoutside) {
0658       completelyinside = false; // single face suffices to reject
0659       return;
0660     }
0661     if (ForInside && !on_surfz) completelyinside &= eqeval < -tolerance; // strictly inside all faces
0662   }
0663 }
0664 
0665 //______________________________________________________________________________
0666 template <typename Real_v>
0667 VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE void GenTrapImplementation::Contains(UnplacedStruct_t const &unplaced,
0668                                                                                   Vector3D<Real_v> const &point,
0669                                                                                   bool &inside)
0670 {
0671   // Use tessellated helper when available (planar case optimization).
0672   // The helper is built on host and copied to device with scalar facet data.
0673   // This path handles all lateral faces as triangles/quads,
0674   // and is typically faster than evaluating bilinear patch equations
0675   // when the shape is purely planar. Z-slab rejection is kept explicit
0676   // to avoid tessellated work when clearly outside along Z.
0677   if (unplaced.fTslHelper) {
0678     // Check Z range
0679     inside = false;
0680     if (Abs(point.z()) > unplaced.fDz) return; // rejected by Z slab
0681     inside = unplaced.fTslHelper->Contains(point);
0682     return;
0683   }
0684   // Generic fallback
0685   bool unused  = false;
0686   bool outside = false;
0687   GenericKernelForContainsAndInside<Real_v, false>(unplaced, point, unused, outside);
0688   inside = !outside;
0689 }
0690 
0691 //______________________________________________________________________________
0692 template <typename Real_v>
0693 VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE void GenTrapImplementation::Inside(UnplacedStruct_t const &unplaced,
0694                                                                                 Vector3D<Real_v> const &point,
0695                                                                                 Inside_t &inside)
0696 {
0697   if (unplaced.fTslHelper) {
0698     // Planar-case dispatcher with tessellated helper
0699     inside         = EInside::kOutside;
0700     Precision safZ = Abs(point.z()) - unplaced.fDz;
0701     if (safZ > kTolerance) return;     // definitely outside along Z
0702     bool insideZ = safZ < -kTolerance; // strictly between the Z planes
0703     inside       = unplaced.fTslHelper->Inside(point);
0704     if (insideZ || inside == EInside::kOutside) return; // kInside is already strict or outside
0705     inside = EInside::kSurface;                         // on the faces within tolerance
0706     return;
0707   }
0708   bool completelyinside;
0709   bool completelyoutside;
0710   GenericKernelForContainsAndInside<Real_v, true>(unplaced, point, completelyinside, completelyoutside);
0711 
0712   // Map masks to EInside classification
0713   inside = EInside::kSurface;
0714   if (completelyoutside) inside = EInside::kOutside;
0715   if (completelyinside) inside = EInside::kInside;
0716 }
0717 
0718 //______________________________________________________________________________
0719 template <typename Real_v>
0720 VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE void GenTrapImplementation::DistanceToIn(UnplacedStruct_t const &unplaced,
0721                                                                                       Vector3D<Real_v> const &point,
0722                                                                                       Vector3D<Real_v> const &direction,
0723                                                                                       Real_v const &stepMax,
0724                                                                                       Real_v &distance)
0725 {
0726   // A fully planar GenericTrap is convex. On the host, clip directly against
0727   // its fixed lateral and z planes to avoid generic facet-container loads. The
0728   // compact facet representation remains faster on CUDA and is used below.
0729 #ifndef VECCORE_CUDA
0730   if (unplaced.fTslHelper && (unplaced.fFlags & 0xF0u) == 0) {
0731     const Real_v invdirz = Real_v(1.) / NonZero(direction.z());
0732     const Real_v pz      = point.z();
0733     distance             = InfinityLength<Real_v>();
0734     if ((Abs(pz) - unplaced.fDz) > -kTolerance && pz * direction.z() >= Real_v(0.)) return;
0735 
0736     const Real_v ddz   = CopySign(unplaced.fDz, invdirz);
0737     const Real_v distz = -(pz + ddz) * invdirz;
0738     Real_v entry       = distz;
0739     Real_v limit       = Min(-(pz - ddz) * invdirz, stepMax);
0740 
0741     VECGEOM_PRAGMA_UNROLL(4)
0742     for (int i = 0; i < 4; ++i) {
0743       const Real_v projection = unplaced.fSurf[i].DotPlaneNormal(direction);
0744       const Real_v planeDist  = unplaced.fSurf[i].EvaluatePlanar(point);
0745       const bool outside      = planeDist > -kTolerance;
0746       if (outside) {
0747         if (projection > -kTolerance) return;
0748         entry = Max(entry, -planeDist / projection);
0749       } else if (projection > kTolerance) {
0750         limit = Min(limit, -planeDist / projection);
0751       }
0752     }
0753     if (entry >= limit - kTolerance) return;
0754     distance = entry;
0755     return;
0756   }
0757 #endif
0758 
0759   // Fast path for planar faces via tessellated helper
0760   if (unplaced.fTslHelper) {
0761     Precision invdirz = 1. / NonZero(direction.z());
0762     // The upper flag bits identify collapsed faces, which are omitted from the
0763     // helper buffer. Otherwise a planar GenericTrap always has four facets.
0764     if ((unplaced.fFlags & 0xF0u) == 0)
0765       distance = unplaced.fTslHelper->DistanceToIn<false, 4>(point, direction, invdirz, stepMax);
0766     else
0767       distance = unplaced.fTslHelper->DistanceToIn<false>(point, direction, invdirz, stepMax);
0768     return;
0769   }
0770   // Summary:
0771   //  1) Handle trivially-inside start (convention distance=-1).
0772   //  2) Intersect the AABB to get an upper bound and early-out if unreachable.
0773   //  3) Try entering through Z slabs (cheap) and return if successful.
0774   //  4) Approact to bounding box distance w/o overshooting into. Improves numerical stability.
0775   //  5) Hoist v-window once, then test lateral faces with [lmin,lmax) window.
0776 #ifndef VECGEOM_NO_WRONGSIDE_CONV
0777   bool completelyinside, completelyoutside;
0778   GenericKernelForContainsAndInside<Real_v, true>(unplaced, point, completelyinside, completelyoutside);
0779 
0780   // Already inside -> signal with -1 as convention
0781   if (completelyinside) {
0782     distance = Real_v(-1.);
0783     return;
0784   }
0785 #endif
0786 
0787   // Intersect with bounding box first to get an upper bound
0788   Real_v bbdistance = Real_v(kInfLength);
0789   BoxImplementation::DistanceToIn(BoxStruct<Precision>(unplaced.fBBdimensions), point - unplaced.fBBorigin, direction,
0790                                   stepMax, bbdistance);
0791 
0792   // Initialize best distance as +inf; if we cannot reach the AABB we cannot hit the solid
0793   distance = InfinityLength<Real_v>();
0794 
0795   // If we cannot reach the AABB, we cannot reach the solid either
0796   bool done = bbdistance >= InfinityLength<Real_v>();
0797   if (done) return;
0798 
0799   // Potential hit with Z planes? Only if we are outside in Z and heading inward
0800   Real_v zsafety = Abs(point.z()) - unplaced.fDz;
0801   bool canhitz   = (zsafety > -kToleranceDist<Real_v>) && (point.z() * direction.z() < 0);
0802 
0803   if (canhitz) {
0804     // Distance to the relevant Z plane (as in Box algorithm)
0805     Real_v next = zsafety / Abs(direction.z());
0806 
0807     // Check containment on the Z plane polygon (top if dir.z>0, bottom otherwise)
0808     auto const vertices = (direction.z() > 0) ? &unplaced.fVertices[0] : &unplaced.fVertices[4];
0809     auto hitz           = InsideSection(point + next * direction, vertices);
0810     if (hitz) {
0811       distance = next;
0812       return;
0813     }
0814   }
0815 
0816   // ---------- Approach to (just outside) the AABB entry --------------
0817   // We start subsequent work from p0 = point + t_approach*dir, with t_approach = max(0, bbdistance - eps),
0818   Real_v t_approach   = Max(Real_v(0), bbdistance - kToleranceArb4<Real_v>);
0819   Vector3D<Real_v> p0 = point + t_approach * direction;
0820   Real_v step_budget  = stepMax - t_approach;
0821   if (step_budget <= Real_v(0)) {
0822     distance = InfinityLength<Real_v>();
0823     return;
0824   }
0825 
0826   // -------- Hoist v(t) in [0,1] window once (face-independent) --------
0827   // We gate by stepMax here to avoid generating candidates beyond the transport step.
0828   // IMPORTANT: We do not cap tmax by the AABB distance; instead we raise lmin later
0829   // with the (possibly finite) AABB entry so that faces cannot return hits before
0830   // the box is actually entered, while still allowing v-window to rule out ranges.
0831   Real_v tmin_v, tmax_v;
0832   if (!GenTrap_VInterval(p0.z(), direction.z(), unplaced.fDz2, step_budget, tmin_v, tmax_v)) {
0833     // Ray never reaches z within [-Dz,+Dz] in forward t within stepMax
0834     return;
0835   }
0836 
0837   // Do not accept hits before we actually pierce the AABB. From p0 the box entry is ~eps_bb ahead.
0838   Real_v lmin = Max(tmin_v, (t_approach > Real_v(0)) ? kToleranceArb4<Real_v> : Real_v(0));
0839   Real_v lmax = tmax_v;
0840   if (lmin > lmax) return;
0841 
0842   // Keep best local distance measured from p0; add t_approach at the end.
0843   Real_v best_local = InfinityLength<Real_v>();
0844 
0845   // Fall back to lateral surfaces and keep the minimum positive distance
0846   // Separate planar/twisted unrolled loops to reduce divergence on device compare to a mixed loop
0847   VECGEOM_PRAGMA_UNROLL(4)
0848   for (auto i = 0; i < 4; ++i) {
0849     if (!unplaced.IsDegenerated(i) && !unplaced.IsTwisted(i)) {
0850       // Planar faces: necessary front-facing check to avoid useless intersections
0851       Real_v dn = unplaced.fSurf[i].DotPlaneNormal(direction);
0852       if (dn >= -kToleranceDist<Real_v>) continue;
0853       // Cap face work by the z-feasible window upper bound
0854       // (we also pass lmin so the face can reject small distances early, before
0855       // any UV or normal work)
0856       Real_v face_limit = Min(best_local, lmax);
0857       best_local        = Min(best_local, DistanceToSurf(unplaced, p0, direction, i, false, lmin, face_limit));
0858     }
0859   }
0860 
0861   VECGEOM_PRAGMA_UNROLL(4)
0862   for (auto i = 0; i < 4; ++i) {
0863     if (!unplaced.IsDegenerated(i) && unplaced.IsTwisted(i)) {
0864       // Twisted faces: use the hoisted v-window to bound exact surface intersections
0865       // As above, we bound by tmax_v and provide lmin=tmin_v to allow
0866       // early rejection prior to UV/normal work.
0867       Real_v face_limit = Min(best_local, lmax);
0868       best_local        = Min(best_local, DistanceToSurf(unplaced, p0, direction, i, false, lmin, face_limit));
0869     }
0870   }
0871 
0872   // Report distance from the original point
0873   distance = (best_local >= InfinityLength<Real_v>()) ? InfinityLength<Real_v>() : (t_approach + best_local);
0874 }
0875 
0876 //______________________________________________________________________________
0877 template <typename Real_v>
0878 VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE void GenTrapImplementation::SetExitHit(UnplacedStruct_t const &unplaced,
0879                                                                                     ExitSurface surface,
0880                                                                                     Vector3D<Real_v> const &hitPoint,
0881                                                                                     SurfaceHitView<Real_v> *hitInfo)
0882 {
0883   if (surface == ExitSurface::kNone) return;
0884 
0885   if (surface == ExitSurface::kZMin || surface == ExitSurface::kZMax) {
0886     hitInfo->SetLeftBehind(true);
0887     if (hitInfo->WantsNormal()) {
0888       const Real_v z = surface == ExitSurface::kZMin ? Real_v(-1.) : Real_v(1.);
0889       hitInfo->SetNormal(Vector3D<Real_v>(Real_v(0.), Real_v(0.), z));
0890     }
0891     return;
0892   }
0893 
0894   const int face = static_cast<int>(surface) - static_cast<int>(ExitSurface::kLateral0);
0895   // A planar lateral supports both convex end sections, hence every section
0896   // obtained by linear interpolation, even when adjacent laterals are twisted.
0897   // A twisted lateral never supports the solid; its normal is the outward
0898   // implicit-surface gradient at the hit point.
0899   const bool twisted = unplaced.IsTwisted(face);
0900   hitInfo->SetLeftBehind(!twisted);
0901   if (!hitInfo->WantsNormal()) return;
0902   if (twisted)
0903     hitInfo->SetNormal(unplaced.fSurf[face].EvaluateGradient(hitPoint).Unit());
0904   else
0905     hitInfo->SetNormal(Vector3D<Real_v>(unplaced.fSurf[face].GetPlaneNormal()));
0906 }
0907 
0908 //______________________________________________________________________________
0909 template <typename Real_v, bool RecordHitInfo>
0910 VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE void GenTrapImplementation::DistanceToOutImpl(
0911     UnplacedStruct_t const &unplaced, Vector3D<Real_v> const &point, Vector3D<Real_v> const &direction,
0912     Real_v const & /*stepMax*/, Real_v &distance, SurfaceHitView<Real_v> *hitInfo)
0913 {
0914   if constexpr (RecordHitInfo) hitInfo->Clear();
0915 
0916   if (unplaced.fTslHelper) {
0917     if constexpr (RecordHitInfo) {
0918       const Real_v safz = Abs(point.z()) - unplaced.fDz;
0919       if (safz > Real_v(kTolerance)) {
0920         distance = Real_v(-kTolerance);
0921         return;
0922       }
0923 
0924       const Real_v vz           = direction.z();
0925       const Real_v capDistance  = vz == Real_v(0.)
0926                                       ? InfinityLength<Real_v>()
0927                                       : Max((CopySign(Real_v(unplaced.fDz), vz) - point.z()) / vz, Real_v(0.));
0928       int face                  = -1;
0929       const Real_v sideDistance = unplaced.fTslHelper->DistanceToOut(point, direction, face);
0930       if (face < 0 && sideDistance < Real_v(0.)) {
0931         distance = sideDistance;
0932         return;
0933       }
0934 
0935       if (sideDistance < capDistance) {
0936         distance = sideDistance;
0937         hitInfo->SetLeftBehind(true);
0938         if (hitInfo->WantsNormal())
0939           hitInfo->SetNormal(Vector3D<Real_v>(unplaced.fTslHelper->GetFacet(face).GetNormal()));
0940       } else {
0941         distance = capDistance;
0942         SetExitHit(unplaced, vz < Real_v(0.) ? ExitSurface::kZMin : ExitSurface::kZMax, point, hitInfo);
0943       }
0944     } else {
0945       distance = unplaced.fTslHelper->DistanceToOut(point, direction);
0946     }
0947     return;
0948   }
0949   // With wrong-side conventions enabled, outside starts return -1. Otherwise
0950   // callers guarantee an inside/surface start. Compute
0951   // the minimum positive distance to any exiting surface (Z slabs + laterals).
0952   // Z slabs are attempted first as they are cheaper; lateral faces use the
0953   // same DistanceToSurf() with in=true and a shrinking lmax=distance.
0954   bool assumeInsideStart = true;
0955 #ifndef VECGEOM_NO_WRONGSIDE_CONV
0956   distance = Real_v(-1.); // default if already outside
0957   bool completelyoutside;
0958   // Enforce the public wrong-side convention when requested. The classification
0959   // also identifies strict interior starts for the direct exit-root path.
0960   GenericKernelForContainsAndInside<Real_v, true>(unplaced, point, assumeInsideStart, completelyoutside);
0961   if (completelyoutside) return;
0962 #endif
0963 
0964   // Candidate intersection with the Z planes (skip if nearly parallel)
0965   Real_v sign         = (direction.z() < 0) ? Real_v(-1.) : Real_v(1.);
0966   Real_v limit        = Real_v(1.); // <- This is a first implementation, we should use the real limit
0967   bool skipZ          = Abs(direction.z()) * limit < kToleranceDist<Real_v>;
0968   distance            = skipZ ? InfinityLength<Real_v>() : (sign * unplaced.fDz - point.z()) / NonZero(direction.z());
0969   ExitSurface surface = skipZ ? ExitSurface::kNone : (sign < Real_v(0.) ? ExitSurface::kZMin : ExitSurface::kZMax);
0970 
0971   // Fall back to lateral surfaces and keep the minimum positive distance
0972   // Separate planar/twisted unrolled loops to reduce divergence on device compare to a mixed loop
0973   VECGEOM_PRAGMA_UNROLL(4)
0974   for (auto i = 0; i < 4; ++i) {
0975     if (!unplaced.IsDegenerated(i) && !unplaced.IsTwisted(i)) {
0976       if constexpr (RecordHitInfo) {
0977         const Real_v candidate =
0978             DistanceToSurf(unplaced, point, direction, i, true, Real_v(0), distance, assumeInsideStart);
0979         if (candidate < distance) {
0980           distance = candidate;
0981           surface  = static_cast<ExitSurface>(static_cast<int>(ExitSurface::kLateral0) + i);
0982         }
0983       } else {
0984         distance =
0985             Min(distance, DistanceToSurf(unplaced, point, direction, i, true, Real_v(0), distance, assumeInsideStart));
0986       }
0987     }
0988   }
0989 
0990   VECGEOM_PRAGMA_UNROLL(4)
0991   for (auto i = 0; i < 4; ++i) {
0992     if (!unplaced.IsDegenerated(i) && unplaced.IsTwisted(i)) {
0993       if constexpr (RecordHitInfo) {
0994         const Real_v candidate =
0995             DistanceToSurf(unplaced, point, direction, i, true, Real_v(0), distance, assumeInsideStart);
0996         if (candidate < distance) {
0997           distance = candidate;
0998           surface  = static_cast<ExitSurface>(static_cast<int>(ExitSurface::kLateral0) + i);
0999         }
1000       } else {
1001         distance =
1002             Min(distance, DistanceToSurf(unplaced, point, direction, i, true, Real_v(0), distance, assumeInsideStart));
1003       }
1004     }
1005   }
1006 
1007   if constexpr (RecordHitInfo) SetExitHit(unplaced, surface, point + distance * direction, hitInfo);
1008 }
1009 
1010 //______________________________________________________________________________
1011 template <typename Real_v>
1012 VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE void GenTrapImplementation::DistanceToOut(
1013     UnplacedStruct_t const &unplaced, Vector3D<Real_v> const &point, Vector3D<Real_v> const &direction,
1014     Real_v const &stepMax, Real_v &distance, SurfaceHitView<Real_v> *hitInfo)
1015 {
1016   if (hitInfo)
1017     DistanceToOutImpl<Real_v, true>(unplaced, point, direction, stepMax, distance, hitInfo);
1018   else
1019     DistanceToOutImpl<Real_v, false>(unplaced, point, direction, stepMax, distance, nullptr);
1020 }
1021 
1022 //______________________________________________________________________________
1023 template <typename Real_v>
1024 VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE void GenTrapImplementation::SafetyToIn(UnplacedStruct_t const &unplaced,
1025                                                                                     Vector3D<Real_v> const &point,
1026                                                                                     Real_v &safety)
1027 {
1028   if (unplaced.fTslHelper) {
1029     safety = unplaced.fTslHelper->SafetyToIn(point);
1030     return;
1031   }
1032   // If outside the bounding box, use the box safety (cheap and conservative)
1033   bool inside;
1034   BoxImplementation::Contains(BoxStruct<Precision>(unplaced.fBBdimensions), point - unplaced.fBBorigin, inside);
1035   if (!inside) {
1036     // This is not optimal if top and bottom faces are not on top of each other
1037     BoxImplementation::SafetyToIn(BoxStruct<Precision>(unplaced.fBBdimensions), point - unplaced.fBBorigin, safety);
1038     return;
1039   }
1040 
1041   // Combine Z safety with lateral faces using SafetyArb4
1042   safety = Abs(point[2]) - unplaced.fDz;
1043   safety = SafetyArb4(unplaced, point, safety, false);
1044 }
1045 
1046 //______________________________________________________________________________
1047 template <typename Real_v>
1048 VECCORE_ATT_HOST_DEVICE void GenTrapImplementation::SafetyToOut(UnplacedStruct_t const &unplaced,
1049                                                                 Vector3D<Real_v> const &point, Real_v &safety)
1050 {
1051   // Dispatcher for SafetyToOut
1052   if (unplaced.fTslHelper) {
1053     safety = unplaced.fTslHelper->SafetyToOut(point);
1054     return;
1055   }
1056   // Generic implementation for SafetyToOut
1057   // Safety convention:
1058   //  - positive value is a *lower bound* to the distance to exit
1059   //  - for Z, we return signed distance to the nearest slab
1060   //  - if already outside along Z (safety >= -tol), return -1 as sentinel
1061 
1062   // Z safety is simple: distance to nearest top/bottom plane (signed)
1063   safety = Abs(point[2]) - unplaced.fDz;
1064 
1065   // Already outside on Z? return -1 to signal this convention
1066   if (safety > -kTolerance) {
1067     safety = Real_v(-1.);
1068     return;
1069   }
1070 
1071   // Aggregate with lateral faces
1072   safety = SafetyArb4(unplaced, point, safety, true);
1073 }
1074 
1075 //______________________________________________________________________________
1076 template <typename Real_v>
1077 VECCORE_ATT_HOST_DEVICE void GenTrapImplementation::NormalKernel(UnplacedStruct_t const &unplaced,
1078                                                                  Vector3D<Real_v> const &point,
1079                                                                  Vector3D<Real_v> &normal, bool &valid)
1080 {
1081   // Computes the normal on a surface and returns it as a unit vector
1082   // Strategy:
1083   //   * Prefer Z planes when |z| is close to Dz.
1084   //   * Identify incident lateral faces on the section at z and use cached
1085   //     plane normals or implicit gradients, averaging multiple matches.
1086   //   * Fall back to the closest projected edge for unmatched points; twisted
1087   //     fallback faces require (u,v) in a tolerance-expanded [0,1]^2.
1088   valid = true;
1089   normal.Set(0.);
1090 
1091   // First, check proximity to the top/bottom planes
1092   Real_v safz = Abs(unplaced.fDz - Abs(point.z()));
1093   if (safz < kTolerance) {
1094     normal[2] = Sign(point.z());
1095     return;
1096   }
1097 
1098   // Resolve incident lateral faces from the section at z before falling back
1099   // to closest-edge projections. The implicit gradient avoids UV recovery.
1100   Vector2D<Real_v> vert[4];
1101   FillVerticesAtZ(unplaced, point.z(), vert);
1102   int surfaceCount    = 0;
1103   bool firstIsTwisted = false;
1104   if (Abs(point.z()) < unplaced.fDz) {
1105     for (int i = 0; i < 4; ++i) {
1106       if (unplaced.IsDegenerated(i)) continue;
1107 
1108       const int next         = (i + 1) % 4;
1109       const Real_v tolerance = unplaced.IsTwisted(i) ? kToleranceArb4<Real_v> : Real_v(kTolerance);
1110       const Real_v minx      = Min(vert[i].x(), vert[next].x()) - tolerance;
1111       const Real_v maxx      = Max(vert[i].x(), vert[next].x()) + tolerance;
1112       const Real_v miny      = Min(vert[i].y(), vert[next].y()) - tolerance;
1113       const Real_v maxy      = Max(vert[i].y(), vert[next].y()) + tolerance;
1114       if (!(point.x() > minx && point.x() < maxx && point.y() > miny && point.y() < maxy)) continue;
1115 
1116       const bool twisted = unplaced.IsTwisted(i);
1117       if (!twisted) {
1118         if (!(Abs(unplaced.fSurf[i].EvaluatePlanar(point)) < tolerance)) continue;
1119       } else {
1120         const Real_v dx    = vert[next].x() - vert[i].x();
1121         const Real_v dy    = vert[next].y() - vert[i].y();
1122         const Real_v dpx   = point.x() - vert[i].x();
1123         const Real_v dpy   = point.y() - vert[i].y();
1124         const Real_v side  = dx * dpy - dy * dpx;
1125         const Real_v lensq = dx * dx + dy * dy;
1126         if (!(side * side < tolerance * tolerance * lensq)) continue;
1127       }
1128 
1129       const auto faceNormal = twisted ? unplaced.fSurf[i].EvaluateGradient(point) : unplaced.fSurf[i].GetPlaneNormal();
1130       if (surfaceCount == 0) {
1131         normal         = faceNormal;
1132         firstIsTwisted = twisted;
1133       } else {
1134         // Only edge hits normalize inside the loop. A regular face hit needs
1135         // one normalization after selection, including across divergent lanes.
1136         if (surfaceCount == 1 && firstIsTwisted) normal.Normalize();
1137         normal += twisted ? faceNormal.Normalized() : faceNormal;
1138       }
1139       ++surfaceCount;
1140     }
1141   }
1142   if (surfaceCount != 0) {
1143     if (surfaceCount > 1 || firstIsTwisted) normal.Normalize();
1144     return;
1145   }
1146 
1147   int iseg;
1148   GetClosestEdge<Real_v>(point, vert, iseg);
1149 
1150   if (!unplaced.IsTwisted(iseg)) {
1151     // Planar face: use precomputed outward normal
1152     normal = unplaced.fSurf[iseg].GetPlaneNormal();
1153     return;
1154   }
1155 
1156   Real_v u, v;
1157   UNormal(unplaced, point, iseg, normal, u, v);
1158   normal.Normalize();
1159 
1160   // Consider points very near boundaries as valid (u,v within tolerance-extended [0,1])
1161   valid = (u > -kToleranceDist<Real_v>) && (u < 1. + kToleranceDist<Real_v>) && (v > -kToleranceDist<Real_v>) &&
1162           (v < 1. + kToleranceDist<Real_v>);
1163 }
1164 
1165 //______________________________________________________________________________
1166 template <typename Real_v>
1167 VECCORE_ATT_HOST_DEVICE void GenTrapImplementation::GetClosestEdge(Vector3D<Real_v> const &point,
1168                                                                    Vector2D<Real_v> const vertxy[4], int &iseg)
1169 {
1170   // Get index of the edge of the quadrilateral represented by vert closest to point.
1171   iseg = 0;
1172   Real_v lsq, dx, dy, dpx, dpy, u;
1173   Real_v safe = InfinityLength<Real_v>();
1174   Real_v ssq  = InfinityLength<Real_v>();
1175 
1176   for (int i = 0; i < 4; ++i) {
1177     int j = (i + 1) % 4;
1178     dx    = vertxy[j].x() - vertxy[i].x();
1179     dy    = vertxy[j].y() - vertxy[i].y();
1180     dpx   = point.x() - vertxy[i].x();
1181     dpy   = point.y() - vertxy[i].y();
1182     lsq   = dx * dx + dy * dy;
1183 
1184     // Skip degenerated segments
1185     if (lsq < kToleranceDistSquared<Real_v>) continue;
1186 
1187     // Projection fraction of P onto segment [i,j]
1188     u = (dpx * dx + dpy * dy);
1189     if (u > lsq) {
1190       // Outside, closer to vertex j
1191       dpx = point.x() - vertxy[j].x();
1192       dpy = point.y() - vertxy[j].y();
1193     } else if (u >= 0) {
1194       // Projection inside the segment
1195       auto invlsq = Real_v(1.) / lsq;
1196       dpx -= u * dx * invlsq;
1197       dpy -= u * dy * invlsq;
1198     }
1199 
1200     ssq = dpx * dpx + dpy * dpy;
1201     if (ssq < safe) {
1202       safe = ssq;
1203       iseg = i;
1204     }
1205   }
1206 }
1207 
1208 //______________________________________________________________________________
1209 template <typename Real_v>
1210 VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE void GenTrapImplementation::UNormal(UnplacedStruct_t const &unplaced,
1211                                                                                  Vector3D<Real_v> const &point, int i,
1212                                                                                  Vector3D<Real_v> &unorm, Real_v &u,
1213                                                                                  Real_v &v)
1214 {
1215   // Get the (u, v) parameters corresponding to the cartesian point
1216   auto uv = XYZtoUV(unplaced, point, i);
1217   u       = uv[0];
1218   v       = uv[1];
1219 
1220   // Tangent vectors of the bilinear patch
1221   // Use extended caches when available
1222 #if GENTRAP_USE_HYBRID_COEFFS
1223   const auto &E0 = unplaced.fE0[i]; // C - A
1224   const auto &E1 = unplaced.fE1[i]; // D - B
1225   const auto &G0 = unplaced.fG0[i]; // B - A
1226   const auto &G1 = unplaced.fG1[i]; // D - C
1227   auto dPdu      = -(Real_v(1.) - v) * E0 - v * E1;
1228   auto dPdv      = (Real_v(1.) - u) * G0 + u * G1;
1229 #else
1230   auto j = (i + 1) % 4;
1231   // Corner notation: face spans A->C on bottom, B->D on top
1232   auto const &A = unplaced.fVertices[i];
1233   auto const &C = unplaced.fVertices[j];
1234   auto const &B = unplaced.fVertices[i + 4];
1235   auto const &D = unplaced.fVertices[j + 4];
1236   auto dPdu     = -(Real_v(1.) - v) * (C - A) - v * (D - B);
1237   auto dPdv     = (Real_v(1.) - u) * (B - A) + u * (D - C);
1238 #endif
1239 
1240   // Un-normalized outward normal
1241   unorm = dPdu.Cross(dPdv);
1242 }
1243 
1244 //______________________________________________________________________________
1245 template <typename Real_v>
1246 VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE bool GenTrapImplementation::InsideSection(Vector3D<Real_v> const &point,
1247                                                                                        Vector3D<Real_v> const v[4])
1248 {
1249   bool inside = true;
1250   bool degen  = true;
1251 
1252   // Half-plane test around the quadrilateral; uses robust cross/length checks
1253   for (int i = 0; i < 4; ++i) {
1254     const auto vij = v[(i + 1) % 4] - v[i];
1255     auto len2      = vij.Mag2();
1256     if (len2 < kToleranceDistSquared<Real_v>) continue; // degenerate edge
1257     degen      = false;
1258     auto cross = (point - v[i]).CrossZ(vij);
1259     inside     = cross * cross >= kToleranceDistSquared<Real_v> * len2 ? (cross >= 0) : false;
1260     if (!inside) break; // early exit if outside any edge
1261   }
1262   if (degen) return false; // degenerate polygon is treated as outside
1263   return inside;
1264 }
1265 
1266 //______________________________________________________________________________
1267 template <typename Real_v>
1268 VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE void GenTrapImplementation::FillVerticesAtZ(
1269     UnplacedStruct_t const &unplaced, Real_v z, Vector2D<Real_v> vertices[4])
1270 {
1271   // Interpolate XY vertices along generators to the specified z-plane
1272   for (int i = 0; i < 4; i++)
1273     vertices[i] = unplaced.fMidXY[i] + unplaced.fT[i] * z;
1274 }
1275 
1276 //______________________________________________________________________________
1277 template <typename Real_v>
1278 VECCORE_ATT_HOST_DEVICE Vector2D<Real_v> GenTrapImplementation::XYZtoUV(UnplacedStruct_t const &unplaced,
1279                                                                         Vector3D<Real_v> const &point, int i)
1280 {
1281   // Parametrize v from z: bottom plane z=-Dz -> v=0, top plane z=+Dz -> v=1
1282   Real_v v = unplaced.fDz2 * (point[2] + unplaced.fDz);
1283 
1284   // Points E, F on the generators (A, C) and (B, D) at z = point[2]
1285 #if GENTRAP_USE_HYBRID_COEFFS
1286   const auto &A  = unplaced.fVertices[i];
1287   const auto &G0 = unplaced.fG0[i];                // B - A
1288   const auto &E0 = unplaced.fE0[i];                // C - A
1289   const auto &E1 = unplaced.fE1[i];                // D - B
1290   auto E         = A + v * G0;                     // (1-v)A + vB
1291   auto EF        = (Real_v(1.) - v) * E0 + v * E1; // F - E but stable form
1292 #else
1293   auto j  = (i + 1) % 4;
1294   auto E  = (1. - v) * unplaced.fVertices[i] + v * unplaced.fVertices[i + 4];
1295   auto F  = (1. - v) * unplaced.fVertices[j] + v * unplaced.fVertices[j + 4];
1296   auto EF = F - E;
1297 #endif
1298   auto EP = point - E;
1299 
1300   // Project along EF to obtain u in [0,1]
1301   auto u = EP.Dot(EF) / NonZero(EF.Dot(EF));
1302   return Vector2D<Real_v>(u, v);
1303 }
1304 
1305 //______________________________________________________________________________
1306 template <typename Real_v>
1307 VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE bool GenTrapImplementation::InSurfLimits(UnplacedStruct_t const &unplaced,
1308                                                                                       Vector3D<Real_v> const &point,
1309                                                                                       int isurf)
1310 {
1311   auto uv = XYZtoUV(unplaced, point, isurf);
1312   // Tolerant test against the unit square in (u,v). This admits points that
1313   // are numerically on the boundaries (within kToleranceDist) as "in".
1314   bool inside = (uv[0] > -kToleranceDist<Real_v>) && (uv[0] < Real_v(1.) + kToleranceDist<Real_v>) &&
1315                 (uv[1] > -kToleranceDist<Real_v>) && (uv[1] < Real_v(1.) + kToleranceDist<Real_v>);
1316   return inside;
1317 }
1318 
1319 //______________________________________________________________________________
1320 template <typename Real_v>
1321 VECGEOM_FORCE_INLINE VECCORE_ATT_HOST_DEVICE Real_v GenTrapImplementation::SafetyArb4(UnplacedStruct_t const &unplaced,
1322                                                                                       Vector3D<Real_v> const &point,
1323                                                                                       Real_v safmax, bool inside)
1324 {
1325   // See: https://gitlab.cern.ch/geant4/geant4-dev/-/merge_requests/5261
1326   Real_v safety = safmax;
1327 
1328   // Aggregate per-face conservative signed safeties
1329   VECGEOM_PRAGMA_UNROLL(4)
1330   for (int i = 0; i < 4; i++) {
1331     if (!unplaced.IsDegenerated(i) && !unplaced.IsTwisted(i)) {
1332       // Planar faces: signed distance to plane using stored outward normal
1333       Real_v sface = unplaced.fSurf[i].EvaluatePlanar(point);
1334       safety       = Max(safety, sface);
1335     }
1336   }
1337 
1338   VECGEOM_PRAGMA_UNROLL(4)
1339   // Twisted bilinear faces: use Lipschitz bound of the implicit function
1340   // Note: We could replace this for slightly twisted faces with the much cheaper
1341   //       but less precise: unplaced.fMesh[i].FastSignedSafety(point, inside);
1342   for (int i = 0; i < 4; i++) {
1343     if (!unplaced.IsDegenerated(i) && unplaced.IsTwisted(i)) {
1344       // Outside -> a face can only help if f(point) > 0
1345       if (!inside && unplaced.fSurf[i].Evaluate(point) <= Real_v(0)) continue;
1346       Real_v sface = unplaced.fSurf[i].SafetyLipschitz(point);
1347       safety       = Max(safety, sface);
1348     }
1349   }
1350 
1351   // Return signed conservative safety: negative when inside, positive outside.
1352   return (inside) ? -safety : safety;
1353 }
1354 
1355 } // namespace VECGEOM_IMPL_NAMESPACE
1356 } // namespace vecgeom
1357 
1358 #endif /* GENTRAPIMPLEMENTATION_H_ */