ERF
Energy Research and Forecasting: An Atmospheric Modeling Code
ERF_EBIFBuildings.H
Go to the documentation of this file.
1 /**
2  * \file ERF_EBIFBuildings.H
3  * \brief Defines the implicit function wrapper for STL-based building geometry.
4  *
5  * This file provides a host-side BuildingsIF owner and a GPU-copyable evaluator
6  * that wrap AMReX's STL infrastructure
7  * to enable 3D building geometry representation in ERF. Unlike the 2D height-based
8  * TerrainIF approach, this provides accurate representation of vertical walls and
9  * complex building structures.
10  */
11 
12 #ifndef ERF_BUILDINGS_IF_H_
13 #define ERF_BUILDINGS_IF_H_
14 
15 #include <AMReX_EB_STL_utils.H>
16 #include <AMReX_EB2_IF_Base.H>
17 #include <AMReX_Geometry.H>
18 #include <AMReX_MultiFab.H>
19 #include <AMReX_FArrayBox.H>
20 #include <AMReX_BoxArray.H>
21 #include <AMReX_BoxList.H>
22 #include <AMReX_DistributionMapping.H>
23 
24 #include <cmath>
25 #include <type_traits>
26 #include <string>
27 #include <memory>
28 #include <numeric> // for std::iota
29 
30 /**
31  * \brief Non-owning, GPU-copyable evaluator of the sampled buildings levelset.
32  *
33  * BuildingsIF owns the data. Copies of this functor only copy its array view,
34  * bounds and grid spacing, so GeometryShop can capture it in device kernels.
35  */
36 class BuildingsLevelsetIF : public amrex::GPUable
37 {
38 public:
39  /**
40  * \brief Evaluate signed distance at a point.
41  *
42  * \param x Physical x-coordinate [m]
43  * \param y Physical y-coordinate [m]
44  * \param z Physical z-coordinate [m]
45  * \return Signed distance value: >0 inside building, <0 in fluid, =0 at boundary.
46  *
47  * This operator performs trilinear interpolation of the pre-sampled signed
48  * distance field. For points outside the sampled domain, it returns a
49  * negative value (fluid region).
50  *
51  * Note: The signed distance field is computed in parallel across ranks
52  * during construction, then replicated for fast operator() access.
53  */
54  AMREX_GPU_HOST_DEVICE inline
55  amrex::Real operator() (AMREX_D_DECL(amrex::Real x,
56  amrex::Real y,
57  amrex::Real z)) const noexcept
58  {
59  using namespace amrex;
60 
61  // fillSignedDistance samples at prob_lo + (index + 0.5) * dx.
62  // Convert physical coordinates to continuous cell-centered indices.
63  Real i_real = (x - m_problo[0]) / m_dx[0] - 0.5;
64  Real j_real = (y - m_problo[1]) / m_dx[1] - 0.5;
65  Real k_real = (z - m_problo[2]) / m_dx[2] - 0.5;
66 
67  // Get integer cell indices
68  int i = static_cast<int>(std::floor(i_real));
69  int j = static_cast<int>(std::floor(j_real));
70  int k = static_cast<int>(std::floor(k_real));
71 
72  // Check if point is within data bounds
73  if (!m_data_box.contains(IntVect(AMREX_D_DECL(i, j, k))) ||
74  !m_data_box.contains(IntVect(AMREX_D_DECL(i + 1, j + 1, k + 1)))) {
75  // Outside sampled region - assume fluid (negative distance)
76  return -1.0;
77  }
78 
79  // Trilinear interpolation weights
80  Real wx = i_real - static_cast<Real>(i);
81  Real wy = j_real - static_cast<Real>(j);
82  Real wz = k_real - static_cast<Real>(k);
83 
84  // Access replicated levelset data
85  auto const& arr = m_local_array;
86 
87  // Trilinear interpolation
88  Real phi_000 = arr(i, j, k);
89  Real phi_100 = arr(i + 1, j, k);
90  Real phi_010 = arr(i, j + 1, k);
91  Real phi_110 = arr(i + 1, j + 1, k);
92  Real phi_001 = arr(i, j, k + 1);
93  Real phi_101 = arr(i + 1, j, k + 1);
94  Real phi_011 = arr(i, j + 1, k + 1);
95  Real phi_111 = arr(i + 1, j + 1, k + 1);
96 
97  Real phi_00 = phi_000 * (1.0 - wx) + phi_100 * wx;
98  Real phi_01 = phi_001 * (1.0 - wx) + phi_101 * wx;
99  Real phi_10 = phi_010 * (1.0 - wx) + phi_110 * wx;
100  Real phi_11 = phi_011 * (1.0 - wx) + phi_111 * wx;
101 
102  Real phi_0 = phi_00 * (1.0 - wy) + phi_10 * wy;
103  Real phi_1 = phi_01 * (1.0 - wy) + phi_11 * wy;
104 
105  Real phi = phi_0 * (1.0 - wz) + phi_1 * wz;
106 
107  // fillSignedDistance has the opposite sign to STLtools::fillFab,
108  // including with reversed normals. Match EB: positive solid, negative fluid.
109  return -phi;
110  }
111 
112  /**
113  * \brief Evaluate signed distance at a point array.
114  *
115  * \param p Physical coordinate array [x, y, z] in meters.
116  * \return Signed distance value.
117  */
118  AMREX_GPU_HOST_DEVICE inline
119  amrex::Real operator() (const amrex::RealArray& p) const noexcept
120  {
121  return this->operator()(AMREX_D_DECL(p[0], p[1], p[2]));
122  }
123 
124 private:
125  friend class BuildingsIF;
126 
127  //! Bounding box of sampled data
128  amrex::Box m_data_box;
129 
130  //! Cached geometry data for GPU-compatible access
131  amrex::GpuArray<amrex::Real, AMREX_SPACEDIM> m_problo;
132  amrex::GpuArray<amrex::Real, AMREX_SPACEDIM> m_dx;
133 
134  //! Local array view for GPU-compatible operator() access
135  amrex::Array4<const amrex::Real> m_local_array;
136 };
137 
138 static_assert(std::is_trivially_copyable_v<BuildingsLevelsetIF>,
139  "The buildings evaluator must be copyable into GPU kernels");
140 
141 /**
142  * \brief Buildings implicit function backed by STL triangle mesh.
143  *
144  * This host-side class owns the sampled data for building geometry
145  * loaded from STL files. It uses AMReX's STL infrastructure with BVH
146  * (Bounding Volume Hierarchy) acceleration for efficient signed distance queries.
147  *
148  * The evaluator returned by getIF() evaluates signed distance, following the
149  * AMReX EB convention: positive = inside solid (building), zero = boundary,
150  * negative = fluid.
151  *
152  * Note: This class pre-samples the STL geometry onto a reference grid and
153  * interpolates at query points. For very large or complex geometries, consider
154  * using AMReX's IndexSpaceSTL directly instead.
155  */
157 {
158 public:
159  /**
160  * \brief Construct a buildings implicit function from an STL file.
161  *
162  * \param stl_file Path to the STL mesh file (binary or ASCII format).
163  * \param scale Uniform scaling factor applied to STL coordinates (typically 1.0).
164  * \param center Translation vector to recenter the mesh [m].
165  * \param reverse_normal Non-zero to flip triangle normals if needed.
166  * \param geom Domain geometry for grid setup and BVH optimization.
167  *
168  * The constructor:
169  * 1. Loads the STL file using AMReX::STLtools
170  * 2. Builds a BVH acceleration structure for fast distance queries
171  * 3. Pre-samples signed distances onto a reference grid
172  * 4. Stores interpolation data for the evaluator returned by getIF()
173  */
174  BuildingsIF (std::string const& stl_file,
175  amrex::Real scale,
176  amrex::Array<amrex::Real, 3> const& center,
177  int reverse_normal,
178  amrex::Geometry const& geom)
179  : m_geom(geom)
180  {
181  using namespace amrex;
182 
183  // Load STL file with BVH optimization
184  // This broadcasts triangle data to all ranks internally
185  m_stl_tools.setBVHOptimization(true);
186  m_stl_tools.read_stl_file(stl_file, scale, center, reverse_normal);
187 
188  // Pre-sample signed distance field onto a reference grid
189  // This grid covers the entire domain with sufficient resolution
190  // to capture building features (match computational grid)
191  Box const& domain = geom.Domain();
192  IntVect ngrow_vec(2); // Ghost cells for interpolation
193 
194  Box sampled_box = domain;
195  sampled_box.grow(ngrow_vec);
196 
197  // Create distributed BoxArray and DistributionMapping for parallel computation
198  // Chunk the domain into reasonable-sized boxes for load balancing
199  BoxArray ba(sampled_box);
200  ba.maxSize(32);
201  DistributionMapping dm(ba);
202 
203  // Create distributed MultiFab to hold signed distance values
204  // Each rank will compute its portion in parallel
205  MultiFab mf_distributed(ba, dm, 1, ngrow_vec);
206 
207  // Compute signed distances in parallel across all ranks
208  // fillSignedDistance uses ParallelFor internally, distributing work
209  // across the MultiFab's boxes according to the DistributionMapping
210  m_stl_tools.fillSignedDistance(mf_distributed, ngrow_vec, geom);
211 
212  // Now create a replicated MultiFab where each rank has a copy of the full domain
213  // This is needed because operator() must access data locally (no MPI in GPU kernels)
214 
215  // Create BoxArray with one box per rank, all covering the same spatial region
216  int nprocs = ParallelDescriptor::NProcs();
217  Vector<Box> boxes(nprocs, sampled_box); // All boxes cover the full domain
218  BoxList bl;
219  for (const auto& bx : boxes) {
220  bl.push_back(bx);
221  }
222  BoxArray ba_replicated(std::move(bl));
223 
224  // Create DistributionMapping so each rank owns exactly one box
225  Vector<int> pmap(nprocs);
226  std::iota(pmap.begin(), pmap.end(), 0); // pmap = [0, 1, 2, ..., nprocs-1]
227  DistributionMapping dm_replicated(std::move(pmap));
228 
229  // Each rank will own one box covering the full domain
230  m_levelset_mf = std::make_shared<MultiFab>(ba_replicated, dm_replicated, 1, 0);
231 
232  // ParallelCopy from distributed to replicated
233  // Source: mf_distributed (each rank has different spatial portions)
234  // Dest: m_levelset_mf (each rank will receive the full domain)
235  IntVect dst_nghost(0);
236  m_levelset_mf->ParallelCopy(mf_distributed, 0, 0, 1, ngrow_vec, dst_nghost);
237 
238  // Store bounds for interpolation
239  m_if.m_data_box = sampled_box;
240 
241  // Cache geometry data for GPU-compatible access
242  const Real* problo_ptr = geom.ProbLo();
243  const Real* dx_ptr = geom.CellSize();
244  for (int d = 0; d < AMREX_SPACEDIM; ++d) {
245  m_if.m_problo[d] = problo_ptr[d];
246  m_if.m_dx[d] = dx_ptr[d];
247  }
248 
249  // Set up local array view for operator() access
250  // Each rank iterates its own local box (which contains the full domain)
251  for (MFIter mfi(*m_levelset_mf); mfi.isValid(); ++mfi) {
252  m_if.m_local_array = (*m_levelset_mf)[mfi].const_array();
253  break; // Only one box per rank
254  }
255  }
256 
257  /**
258  * \brief Return the GPU-copyable evaluator for the sampled levelset.
259  *
260  * This owner must remain alive until all evaluations have finished, including
261  * EB2::Build and EB2::BuildFC. In GPU builds, evaluate on the device.
262  * Calling it on a temporary owner does not compile, since the evaluator
263  * would point at the owner's freed levelset.
264  */
265  BuildingsLevelsetIF getIF () const& noexcept { return m_if; }
266  BuildingsLevelsetIF getIF () const&& = delete;
267 
268 protected:
269  //! Domain geometry (for coordinate transformations)
270  amrex::Geometry m_geom;
271 
272  //! STL tools object (for loading and processing STL files)
273  amrex::STLtools m_stl_tools;
274 
275  //! Owns the replicated levelset referenced by m_if on each rank.
276  std::shared_ptr<amrex::MultiFab> m_levelset_mf;
277 
279 };
280 
281 #endif // ERF_BUILDINGS_IF_H_
Buildings implicit function backed by STL triangle mesh.
Definition: ERF_EBIFBuildings.H:157
BuildingsLevelsetIF getIF() const &noexcept
Return the GPU-copyable evaluator for the sampled levelset.
Definition: ERF_EBIFBuildings.H:265
BuildingsIF(std::string const &stl_file, amrex::Real scale, amrex::Array< amrex::Real, 3 > const &center, int reverse_normal, amrex::Geometry const &geom)
Construct a buildings implicit function from an STL file.
Definition: ERF_EBIFBuildings.H:174
BuildingsLevelsetIF getIF() const &&=delete
Non-owning, GPU-copyable evaluator of the sampled buildings levelset.
Definition: ERF_EBIFBuildings.H:37
amrex::Array4< const amrex::Real > m_local_array
Local array view for GPU-compatible operator() access.
Definition: ERF_EBIFBuildings.H:135
amrex::GpuArray< amrex::Real, AMREX_SPACEDIM > m_problo
Cached geometry data for GPU-compatible access.
Definition: ERF_EBIFBuildings.H:131
amrex::Box m_data_box
Bounding box of sampled data.
Definition: ERF_EBIFBuildings.H:128
amrex::GpuArray< amrex::Real, AMREX_SPACEDIM > m_dx
Definition: ERF_EBIFBuildings.H:132
AMREX_GPU_HOST_DEVICE amrex::Real operator()(AMREX_D_DECL(amrex::Real x, amrex::Real y, amrex::Real z)) const noexcept
Evaluate signed distance at a point.
Definition: ERF_EBIFBuildings.H:55
@ p
Definition: ERF_WSM6.H:303
Definition: ERF_ConsoleIO.cpp:17
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE amrex::Real phi(amrex::Real d, amrex::Real z0, amrex::Real psi) noexcept
Definition: ERF_ImmersedWallCell.H:176