Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-18 10:33:21

0001 //------------------------------- -*- C++ -*- -------------------------------//
0002 // Copyright Celeritas contributors: see top-level COPYRIGHT file for details
0003 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
0004 //---------------------------------------------------------------------------//
0005 //! \file geocel/vg/VecgeomTrackView.hh
0006 //---------------------------------------------------------------------------//
0007 #pragma once
0008 
0009 #include <VecGeom/base/Version.h>
0010 // NOTE: must include Global before most other vecgeom/veccore includes
0011 #include <VecGeom/base/Global.h>
0012 #include <VecGeom/volumes/LogicalVolume.h>
0013 #include <VecGeom/volumes/PlacedVolume.h>
0014 
0015 #include "corecel/Config.hh"
0016 
0017 #include "corecel/Macros.hh"
0018 #include "corecel/Types.hh"
0019 #include "corecel/cont/Span.hh"
0020 #include "corecel/math/ArraySoftUnit.hh"
0021 #include "corecel/math/ArrayUtils.hh"
0022 #include "corecel/sys/ThreadId.hh"
0023 #include "geocel/Types.hh"
0024 #include "geocel/detail/LengthUnits.hh"
0025 
0026 #include "VecgeomData.hh"
0027 #include "VecgeomTypes.hh"
0028 
0029 #if CELERITAS_VECGEOM_VERSION < 0x020000
0030 #    include "detail/BVHNavigator.hh"
0031 #else
0032 #    include "detail/SolidsNavigator.hh"
0033 #endif
0034 
0035 #if CELER_VGNAV == CELER_VGNAV_PATH
0036 #    include <VecGeom/navigation/NavStatePath.h>
0037 #endif
0038 
0039 #if !CELER_DEVICE_COMPILE
0040 #    include "corecel/io/Logger.hh"
0041 #    include "corecel/io/Repr.hh"
0042 #endif
0043 
0044 namespace celeritas
0045 {
0046 //---------------------------------------------------------------------------//
0047 /*!
0048  * Navigate through a VecGeom geometry on a single thread.
0049  *
0050  * For a description of ordering requirements, see:
0051  * \sa OrangeTrackView
0052  *
0053  * \code
0054     VecgeomTrackView geom(vg_params_ref, vg_state_ref, trackslot_id);
0055    \endcode
0056  *
0057  * The "next distance" is cached as part of `find_next_step`, but it is only
0058  * used when the immediate next call is `move_to_boundary`.
0059  *
0060  * \todo Normal calculation is not yet implemented!! Optical surface physics
0061  * will not work.
0062  */
0063 class VecgeomTrackView
0064 {
0065   public:
0066     //!@{
0067     //! \name Type aliases
0068     using Initializer_t = GeoTrackInitializer;
0069     using ParamsRef = NativeCRef<VecgeomParamsData>;
0070     using StateRef = NativeRef<VecgeomStateData>;
0071 #if CELERITAS_VECGEOM_VERSION < 0x020000
0072     using Navigator = celeritas::detail::BVHNavigator;
0073 #else
0074     using Navigator = celeritas::detail::SolidsNavigator;
0075 #endif
0076     using ImplVolInstanceId = VgVolumeInstanceId;
0077     using real_type = vg_real_type;
0078     //!@}
0079 
0080   public:
0081     // Construct from persistent and state data
0082     inline CELER_FUNCTION VecgeomTrackView(
0083         ParamsRef const& data, StateRef const& stateview, TrackSlotId tid);
0084 
0085     // Initialize the state
0086     inline CELER_FUNCTION VecgeomTrackView& operator=(
0087         Initializer_t const& init);
0088 
0089     //// STATIC ACCESSORS ////
0090 
0091     //! A tiny push to make sure tracks do not get stuck at boundaries
0092     //! (a physical length, so that it is resolvable in any unit system)
0093     static CELER_CONSTEXPR_FUNCTION real_type extra_push()
0094     {
0095         return real_type{1e-13} * lengthunits::centimeter;
0096     }
0097 
0098     //// ACCESSORS ////
0099 
0100     //!@{
0101     //! State accessors
0102     CELER_FORCEINLINE_FUNCTION Real3 const& pos() const { return pos_; }
0103     CELER_FORCEINLINE_FUNCTION Real3 const& dir() const { return dir_; }
0104     //!@}
0105 
0106     // Get the canonical volume ID in the current impl volume
0107     inline CELER_FUNCTION VolumeId volume_id() const;
0108     // Get the ID of the current volume instance
0109     inline CELER_FUNCTION VolumeInstanceId volume_instance_id() const;
0110     // Get the depth in the geometry hierarchy
0111     inline CELER_FUNCTION VolumeLevelId volume_level() const;
0112     // Get the volume instance ID for all levels
0113     inline CELER_FUNCTION void volume_instance_id(
0114         Span<VolumeInstanceId> levels) const;
0115     // Visit every volume instance in the track's path, including world
0116     template<class F>
0117     inline CELER_FUNCTION void foreach_volume_path(F&& visit) const;
0118 
0119     // Get the current volume's ID
0120     inline CELER_FUNCTION ImplVolumeId impl_volume_id() const;
0121     // The current surface ID
0122     inline CELER_FUNCTION ImplSurfaceId impl_surface_id() const;
0123     // After 'find_next_step', the next straight-line surface
0124     inline CELER_FUNCTION ImplSurfaceId next_impl_surface_id() const;
0125 
0126     // Whether the track is outside the valid geometry region
0127     CELER_FORCEINLINE_FUNCTION bool is_outside() const;
0128     // Whether the track is exactly on a surface
0129     CELER_FORCEINLINE_FUNCTION bool is_on_boundary() const;
0130     //! Whether the last operation resulted in an error
0131     CELER_FORCEINLINE_FUNCTION bool failed() const { return failed_; }
0132     // Get the normal vector of the current surface
0133     inline CELER_FUNCTION Real3 normal() const;
0134 
0135     //// OPERATIONS ////
0136 
0137     // Find the distance to the next boundary, up to and including a step
0138     inline CELER_FUNCTION Propagation find_next_step(real_type max_step);
0139 
0140     // Find the safety at the current position (infinite max)
0141     inline CELER_FUNCTION real_type find_safety();
0142 
0143     // Find the safety at the current position up to a maximum step distance
0144     inline CELER_FUNCTION real_type find_safety(real_type max_step);
0145 
0146     // Move to the boundary in preparation for crossing it
0147     inline CELER_FUNCTION void move_to_boundary();
0148 
0149     // Move within the volume
0150     inline CELER_FUNCTION void move_internal(real_type step);
0151 
0152     // Move within the volume to a specific point
0153     inline CELER_FUNCTION void move_internal(Real3 const& pos);
0154 
0155     // Cross from one side of the current surface to the other
0156     inline CELER_FUNCTION void cross_boundary();
0157 
0158     // Change direction
0159     inline CELER_FUNCTION void set_dir(Real3 const& newdir);
0160 
0161   private:
0162     //// TYPES ////
0163 
0164     using VgLogVol = VgLogicalVolume<MemSpace::native>;
0165     using VgPlacedVol = VgPlacedVolume<MemSpace::native>;
0166 
0167     //// DATA ////
0168 
0169     //! Shared/persistent geometry data
0170     ParamsRef const& params_;
0171     StateRef const& state_;
0172     TrackSlotId tid_;
0173 
0174     //!@{
0175     //! Referenced thread-local data
0176     VgNavState& vgstate_;
0177     VgNavState& vgnext_;
0178     Real3& pos_;
0179     Real3& dir_;
0180 
0181     //!@}
0182 
0183     // Temporary data
0184     real_type next_step_{0};
0185     bool failed_{false};
0186 
0187     //// HELPER FUNCTIONS ////
0188 
0189     // Whether any next distance-to-boundary has been found
0190     inline CELER_FUNCTION bool has_next_step() const;
0191 
0192     // Whether the next distance-to-boundary is to a surface
0193     inline CELER_FUNCTION bool is_next_boundary() const;
0194 
0195     // Get a reference to the current volume instance
0196     inline CELER_FUNCTION VgPlacedVol const& physical_volume() const;
0197 
0198     // Get a reference to the current volume
0199     inline CELER_FUNCTION VgLogVol const& logical_volume() const;
0200 };
0201 
0202 //---------------------------------------------------------------------------//
0203 // INLINE DEFINITIONS
0204 //---------------------------------------------------------------------------//
0205 /*!
0206  * Construct from persistent and state data.
0207  */
0208 CELER_FUNCTION VecgeomTrackView::VecgeomTrackView(
0209     ParamsRef const& params, StateRef const& states, TrackSlotId tid)
0210     : params_(params)
0211     , state_(states)
0212     , tid_(tid)
0213     , vgstate_{states.state[tid]}
0214     , vgnext_{states.next_state[tid]}
0215     , pos_(states.pos[tid])
0216     , dir_(states.dir[tid])
0217 {
0218 }
0219 
0220 //---------------------------------------------------------------------------//
0221 /*!
0222  * Construct the state.
0223  *
0224  * If a valid parent ID is provided, the state is constructed from a direction
0225  * and a copy of the parent state.  This is a faster method of creating
0226  * secondaries from a parent that has just been absorbed, or when filling in an
0227  * empty track from a parent that is still alive.
0228  *
0229  * Otherwise, the state is initialized from a starting location and direction,
0230  * which is expensive.
0231  */
0232 CELER_FUNCTION VecgeomTrackView& VecgeomTrackView::operator=(
0233     Initializer_t const& init)
0234 {
0235     CELER_EXPECT(is_soft_unit_vector(init.dir));
0236     failed_ = false;
0237 
0238     // Initialize direction
0239     dir_ = init.dir;
0240 
0241     if (init.parent)
0242     {
0243         // Copy the navigation state and position from the parent state
0244         if (tid_ != init.parent)
0245         {
0246             VecgeomTrackView other(params_, state_, init.parent);
0247             other.vgstate_.CopyTo(&vgstate_);
0248             pos_ = other.pos_;
0249         }
0250         // Set up the next state and initialize the direction
0251         vgnext_ = vgstate_;
0252 
0253         CELER_ENSURE(this->pos() == init.pos);
0254         CELER_ENSURE(!this->has_next_step());
0255         return *this;
0256     }
0257 
0258     // Initialize the state from a position
0259     pos_ = init.pos;
0260 
0261     // Set up current state and locate daughter volume
0262     vgstate_.Clear();
0263     auto const* world = params_.scalars.world<MemSpace::native>();
0264     // LocatePointIn sets `vgstate_`
0265     constexpr bool contains_point = true;
0266     Navigator::LocatePointIn(
0267         world, to_vgvector(pos_), vgstate_, contains_point);
0268 
0269     if (CELER_UNLIKELY(vgstate_.IsOutside()))
0270     {
0271 #if !CELER_DEVICE_COMPILE
0272         auto msg = CELER_LOG_LOCAL(error);
0273         msg << "Failed to initialize geometry state at " << repr(pos_) << ' '
0274             << lengthunits::native_label;
0275 #endif
0276         failed_ = true;
0277     }
0278 
0279     return *this;
0280 }
0281 
0282 //---------------------------------------------------------------------------//
0283 /*!
0284  * Get the volume ID in the current cell.
0285  */
0286 CELER_FORCEINLINE_FUNCTION VolumeId VecgeomTrackView::volume_id() const
0287 {
0288     CELER_EXPECT(!this->is_outside());
0289     CELER_EXPECT(!params_.volumes.empty());
0290 
0291     return params_.volumes[this->impl_volume_id()];
0292 }
0293 
0294 //---------------------------------------------------------------------------//
0295 /*!
0296  * Get the physical volume ID in the current cell.
0297  *
0298  * If built with Geant4, this is the canonical volume instance ID. If built
0299  * with VGDML, this is an "implementation" instance ID.
0300  */
0301 CELER_FUNCTION VolumeInstanceId VecgeomTrackView::volume_instance_id() const
0302 {
0303     CELER_EXPECT(!this->is_outside());
0304     auto ipv_id = id_cast<ImplVolInstanceId>(this->physical_volume().id());
0305     return params_.volume_instances[ipv_id];
0306 }
0307 
0308 //---------------------------------------------------------------------------//
0309 /*!
0310  * Get the depth in the geometry hierarchy.
0311  */
0312 CELER_FUNCTION VolumeLevelId VecgeomTrackView::volume_level() const
0313 {
0314     CELER_EXPECT(!this->is_outside());
0315     auto result = id_cast<VolumeLevelId>(vgstate_.GetLevel());
0316     CELER_ENSURE(result < params_.scalars.num_volume_levels);
0317     return result;
0318 }
0319 
0320 //---------------------------------------------------------------------------//
0321 /*!
0322  * Get the volume instance ID at each volume level.
0323  */
0324 CELER_FUNCTION void VecgeomTrackView::volume_instance_id(
0325     Span<VolumeInstanceId> levels) const
0326 {
0327     this->foreach_volume_path(
0328         [levels](VolumeLevelId lev, VolumeInstanceId vol_inst) {
0329             CELER_EXPECT(lev < levels.size());
0330             CELER_EXPECT(vol_inst);
0331             levels[*lev] = vol_inst;
0332         });
0333 }
0334 
0335 //---------------------------------------------------------------------------//
0336 /*!
0337  * Apply the function with the volume instance ID and level.
0338  *
0339  * This can be used to construct a unique volume instance ID or fill a vector
0340  * with volume levels. It is performed in global-to-local order.
0341  */
0342 template<class F>
0343 CELER_FUNCTION void VecgeomTrackView::foreach_volume_path(F&& visit) const
0344 {
0345     for (auto lev : range(this->volume_level() + 1))
0346     {
0347         VgPlacedVol const* pv = vgstate_.At(*lev);
0348         CELER_ASSERT(pv);
0349         auto ipv_id = id_cast<ImplVolInstanceId>(pv->id());
0350         visit(lev, params_.volume_instances[ipv_id]);
0351     }
0352 }
0353 
0354 //---------------------------------------------------------------------------//
0355 /*!
0356  * Get the volume ID in the current cell.
0357  */
0358 CELER_FORCEINLINE_FUNCTION ImplVolumeId VecgeomTrackView::impl_volume_id() const
0359 {
0360     CELER_EXPECT(!this->is_outside());
0361     return id_cast<ImplVolumeId>(this->logical_volume().id());
0362 }
0363 
0364 //---------------------------------------------------------------------------//
0365 /*!
0366  * The current surface frame ID.
0367  */
0368 CELER_FUNCTION ImplSurfaceId VecgeomTrackView::impl_surface_id() const
0369 {
0370     return {};
0371 }
0372 
0373 //---------------------------------------------------------------------------//
0374 /*!
0375  * After 'find_next_step', the next straight-line surface.
0376  */
0377 CELER_FUNCTION ImplSurfaceId VecgeomTrackView::next_impl_surface_id() const
0378 {
0379     return {};
0380 }
0381 
0382 //---------------------------------------------------------------------------//
0383 /*!
0384  * Whether the track is outside the valid geometry region.
0385  */
0386 CELER_FUNCTION bool VecgeomTrackView::is_outside() const
0387 {
0388     return vgstate_.IsOutside();
0389 }
0390 
0391 //---------------------------------------------------------------------------//
0392 /*!
0393  * Whether the track is on the boundary of a volume.
0394  */
0395 CELER_FUNCTION bool VecgeomTrackView::is_on_boundary() const
0396 {
0397     return vgstate_.IsOnBoundary();
0398 }
0399 
0400 //---------------------------------------------------------------------------//
0401 /*!
0402  * Get the surface normal of the boundary the track is currently on.
0403  */
0404 CELER_FUNCTION Real3 VecgeomTrackView::normal() const
0405 {
0406     // FIXME: temporarily return a bogus but valid surface normal
0407     return this->dir();
0408 }
0409 
0410 //---------------------------------------------------------------------------//
0411 /*!
0412  * Find the distance to the next geometric boundary.
0413  */
0414 CELER_FUNCTION Propagation VecgeomTrackView::find_next_step(real_type max_step)
0415 {
0416     CELER_EXPECT(!this->is_outside());
0417     CELER_EXPECT(max_step > 0);
0418 
0419     // TODO: vgnext is simply copied and the boundary flag optionally set
0420     next_step_ = Navigator::ComputeStepAndNextVolume(
0421         to_vgvector(pos_), to_vgvector(dir_), max_step, vgstate_, vgnext_);
0422 
0423     next_step_ = max(next_step_, this->extra_push());
0424 
0425     if (!this->is_next_boundary())
0426     {
0427         // Soft equivalence between distance and max step is because the
0428         // BVH navigator subtracts and then re-adds a bump distance to the
0429         // step
0430         CELER_ASSERT(soft_equal(next_step_, max(max_step, this->extra_push())));
0431         next_step_ = max_step;
0432     }
0433 
0434     Propagation result;
0435     result.distance = next_step_;
0436     result.boundary = this->is_next_boundary();
0437 
0438     CELER_ENSURE(this->has_next_step());
0439     CELER_ENSURE(result.distance > 0);
0440     CELER_ENSURE(result.distance <= max(max_step, this->extra_push()));
0441     CELER_ENSURE(result.boundary || result.distance == max_step
0442                  || max_step < this->extra_push());
0443     return result;
0444 }
0445 
0446 //---------------------------------------------------------------------------//
0447 /*!
0448  * Find the safety at the current position.
0449  */
0450 CELER_FUNCTION real_type VecgeomTrackView::find_safety()
0451 {
0452     return this->find_safety(vecgeom::kInfLength);
0453 }
0454 
0455 //---------------------------------------------------------------------------//
0456 /*!
0457  * Find the safety at the current position up to a maximum distance.
0458  *
0459  * The safety within a step is only needed up to the end of the physics step
0460  * length.
0461  */
0462 CELER_FUNCTION real_type VecgeomTrackView::find_safety(real_type max_radius)
0463 {
0464     CELER_EXPECT(!this->is_outside());
0465     CELER_EXPECT(!this->is_on_boundary());
0466     CELER_EXPECT(max_radius > 0);
0467 
0468     real_type safety = Navigator::ComputeSafety(
0469         to_vgvector(this->pos()), vgstate_, max_radius);
0470     safety = min<real_type>(safety, max_radius);
0471 
0472     // Since the reported "safety" is negative if we've moved slightly beyond
0473     // the boundary of a solid without crossing it, we must clamp to zero.
0474     return max<real_type>(safety, 0);
0475 }
0476 
0477 //---------------------------------------------------------------------------//
0478 /*!
0479  * Move to the next boundary but don't cross yet.
0480  */
0481 CELER_FUNCTION void VecgeomTrackView::move_to_boundary()
0482 {
0483     CELER_EXPECT(this->has_next_step());
0484     CELER_EXPECT(this->is_next_boundary());
0485 
0486     // Move next step
0487     axpy(next_step_, dir_, &pos_);
0488     next_step_ = 0;
0489     vgstate_.SetBoundaryState(true);
0490 
0491     CELER_ENSURE(this->is_on_boundary());
0492 }
0493 
0494 //---------------------------------------------------------------------------//
0495 /*!
0496  * Cross from one side of the current surface to the other.
0497  *
0498  * The position *must* be on the boundary following a move-to-boundary.
0499  */
0500 CELER_FUNCTION void VecgeomTrackView::cross_boundary()
0501 {
0502     CELER_EXPECT(!this->is_outside());
0503     CELER_EXPECT(this->is_on_boundary());
0504     CELER_EXPECT(this->is_next_boundary());
0505 
0506     // Relocate to next tracking volume (maybe across multiple boundaries)
0507     if (vgnext_.Top() != nullptr)
0508     {
0509         Navigator::RelocateToNextVolume(to_vgvector(this->pos_),
0510                                         to_vgvector(this->dir_),
0511                                         vgstate_,
0512                                         vgnext_);
0513     }
0514 
0515     vgstate_ = vgnext_;
0516 
0517     CELER_ENSURE(this->is_on_boundary());
0518 }
0519 
0520 //---------------------------------------------------------------------------//
0521 /*!
0522  * Move within the current volume.
0523  *
0524  * The straight-line distance *must* be less than the distance to the
0525  * boundary.
0526  */
0527 CELER_FUNCTION void VecgeomTrackView::move_internal(real_type dist)
0528 {
0529     CELER_EXPECT(this->has_next_step());
0530     CELER_EXPECT(dist > 0 && dist <= next_step_);
0531     CELER_EXPECT(dist != next_step_ || !this->is_next_boundary());
0532 
0533     // Move and update next_step_
0534     axpy(dist, dir_, &pos_);
0535     next_step_ -= dist;
0536     vgstate_.SetBoundaryState(false);
0537 
0538     CELER_ENSURE(!this->is_on_boundary());
0539 }
0540 
0541 //---------------------------------------------------------------------------//
0542 /*!
0543  * Move within the current volume to a nearby point.
0544  *
0545  * \warning It's up to the caller to make sure that the position is
0546  * "nearby" and within the same volume.
0547  */
0548 CELER_FUNCTION void VecgeomTrackView::move_internal(Real3 const& pos)
0549 {
0550     pos_ = pos;
0551     next_step_ = 0;
0552     vgstate_.SetBoundaryState(false);
0553 
0554     CELER_ENSURE(!this->is_on_boundary());
0555 }
0556 
0557 //---------------------------------------------------------------------------//
0558 /*!
0559  * Change the track's direction.
0560  *
0561  * This happens after a scattering event or movement inside a magnetic field.
0562  * It resets the calculated distance-to-boundary.
0563  */
0564 CELER_FUNCTION void VecgeomTrackView::set_dir(Real3 const& newdir)
0565 {
0566     CELER_EXPECT(is_soft_unit_vector(newdir));
0567     dir_ = newdir;
0568     next_step_ = 0;
0569 }
0570 
0571 //---------------------------------------------------------------------------//
0572 // PRIVATE MEMBER FUNCTIONS
0573 //---------------------------------------------------------------------------//
0574 /*!
0575  * Whether a next step has been calculated.
0576  */
0577 CELER_FUNCTION bool VecgeomTrackView::has_next_step() const
0578 {
0579     return next_step_ != 0;
0580 }
0581 
0582 //---------------------------------------------------------------------------//
0583 /*!
0584  * Whether the calculated next step will take track to next boundary.
0585  */
0586 CELER_FUNCTION bool VecgeomTrackView::is_next_boundary() const
0587 {
0588     CELER_EXPECT(this->has_next_step() || this->is_on_boundary());
0589     return vgnext_.IsOnBoundary();
0590 }
0591 
0592 //---------------------------------------------------------------------------//
0593 /*!
0594  * Get a reference to the current volume.
0595  */
0596 CELER_FUNCTION auto VecgeomTrackView::physical_volume() const
0597     -> VgPlacedVol const&
0598 {
0599     VgPlacedVol const* physvol_ptr = vgstate_.Top();
0600     CELER_ENSURE(physvol_ptr);
0601     return *physvol_ptr;
0602 }
0603 
0604 //---------------------------------------------------------------------------//
0605 /*!
0606  * Get a reference to the current volume, or to world volume if outside.
0607  */
0608 CELER_FUNCTION auto VecgeomTrackView::logical_volume() const -> VgLogVol const&
0609 {
0610     return *this->physical_volume().GetLogicalVolume();
0611 }
0612 
0613 //---------------------------------------------------------------------------//
0614 }  // namespace celeritas