SPH
SsfToVdb.cpp
Go to the documentation of this file.
1 #include "io/FileSystem.h"
2 #include "io/Output.h"
5 #include "objects/geometry/Box.h"
7 #include "openvdb/openvdb.h"
8 #include "quantities/IMaterial.h"
9 #include "sph/kernel/Kernel.h"
10 #include "system/Factory.h"
11 #include "system/Statistics.h"
12 #include "system/Timer.h"
13 #include "thread/Pool.h"
14 #include <iostream>
15 
16 using namespace Sph;
17 
18 Storage loadSsf(const Path& path) {
19  BinaryInput io;
20  Storage storage;
21  Statistics stats;
22  io.load(path, storage, stats);
23  return storage;
24 }
25 
26 INLINE openvdb::Vec3R vectorToVec3R(const Vector& v) {
27  return openvdb::Vec3R(v[X], v[Y], v[Z]);
28 }
29 
30 struct VdbParams {
31 
32  Box box = Box(Vector(-5.e5_f, -5.e5_f, -3.e5_f), Vector(5.e5_f, 5.e5_f, 3.e5_f));
33 
34  Indices gridDims = Indices(1024);
35 
36  Float surfaceLevel = 0.13_f;
37 };
38 
39 Vector worldToRelative(const Vector& r, const VdbParams& params) {
40  return (r - params.box.lower()) / params.box.size() * Vector(params.gridDims);
41 }
42 
43 Vector relativeToWorld(const Vector& r, const VdbParams& params) {
44  return r * params.box.size() / Vector(params.gridDims) + params.box.lower();
45 }
46 
48  const Vector from = worldToRelative(r - Vector(2._f * r[H]), params);
49  const Vector to = worldToRelative(r + Vector(2._f * r[H]), params);
50  const Indices fromIdxs(ceil(from[X]), ceil(from[Y]), ceil(from[Z]));
51  const Indices toIdxs(floor(to[X]), floor(to[Y]), floor(to[Z]));
52  return { max(fromIdxs, Indices(0._f)), min(toIdxs, params.gridDims - Indices(1)) };
53 }
54 
55 void convert(const Path& path, const VdbParams params) {
56  const Storage storage = loadSsf(path);
57  openvdb::GridPtrVec vdbGrids;
58 
59 
60  openvdb::FloatGrid::Ptr colorField = openvdb::FloatGrid::create(0._f);
61  openvdb::Vec3SGrid::Ptr velocityField = openvdb::Vec3SGrid::create(vectorToVec3R(Vector(0._f)));
62  openvdb::FloatGrid::Ptr energyField = openvdb::FloatGrid::create(0._f);
63 
64  typename openvdb::FloatGrid::Accessor colorAccessor = colorField->getAccessor();
65  colorField->setName("Density");
66  colorField->setGridClass(openvdb::GRID_LEVEL_SET);
67 
68  typename openvdb::Vec3SGrid::Accessor velocityAccessor = velocityField->getAccessor();
69  velocityField->setName("Velocity");
70 
71  typename openvdb::FloatGrid::Accessor energyAccessor = energyField->getAccessor();
72  energyField->setName("Emission");
73 
74 
76  // ArrayView<const Vector> v = storage.getDt<Vector>(QuantityId::POSITION);
79 
80  const Float u_iv = storage.getMaterial(0)->getParam<Float>(BodySettingsId::TILLOTSON_ENERGY_IV);
81 
82 
83  const Size gridSize = max(params.gridDims[0], params.gridDims[1], params.gridDims[2]);
84 
85  struct Record {
86  float density = 0.f;
87  float energy = 0.f;
88  };
89 
90  SparseGrid<Record> grid(gridSize);
91  // Grid<Vector> velocity(params.gridDims, Vector(0._f));
92 
93  LutKernel<3> kernel = Factory::getKernel<3>(RunSettings::getDefaults());
94 
95  // Timer timer;
96 
97  for (Size i = 0; i < r.size(); ++i) {
98  Indices from, to;
99  tieToTuple(from, to) = getParticleBox(r[i], params);
100  for (int x = from[X]; x <= to[X]; ++x) {
101  for (int y = from[Y]; y <= to[Y]; ++y) {
102  for (int z = from[Z]; z <= to[Z]; ++z) {
103  const Indices idxs(x, y, z);
104  const Vector pos = relativeToWorld(idxs, params);
105  const Float w = kernel.value(r[i] - pos, r[i][H]);
106  const Float p = m[i] / 2700._f;
107  Record& record = grid[idxs];
108  record.density += p * w;
109  record.energy += u[i] * p * w;
110  // velocity[idxs] += v[j] * p * w;
111  }
112  }
113  }
114  }
115  // std::cout << "Grid created in " << timer.elapsed(TimerUnit::MILLISECOND) << "ms" << std::endl;
116 
117  // timer.restart();
118  /* for (int x = 0; x < params.gridDims[X]; ++x) {
119  for (int y = 0; y < params.gridDims[Y]; ++y) {
120  for (int z = 0; z < params.gridDims[Z]; ++z) {*/
121  grid.iterate([&](const Record& record, const Indices idxs) {
122  ASSERT(isReal(record.density));
123  ASSERT(isReal(record.energy));
124  openvdb::Coord coords(idxs[0], idxs[1], idxs[2]);
125 
126  if (record.density < params.surfaceLevel) {
127  return;
128  }
129  colorAccessor.setValue(coords, record.density - params.surfaceLevel);
130 
131  // const Vector v = velocity[idxs] / field;
132  // velocityAccessor.setValue(coords, vectorToVec3R(v));
133 
134  const Float e = log(1._f + record.energy / record.density / u_iv);
135  energyAccessor.setValue(coords, e);
136  });
137 
138  // zstd::cout << "Converted to VDB grid in " << timer.elapsed(TimerUnit::MILLISECOND) << "ms" <<
139  // std::endl;
140 
141  /* }
142  }
143  }*/
144 
145 
146  vdbGrids.push_back(colorField);
147  // grids.push_back(velocityField);
148  vdbGrids.push_back(energyField);
149 
150  Path vdbPath = path;
151  vdbPath.replaceExtension("vdb");
152  openvdb::io::File vdbFile(vdbPath.native());
153  vdbFile.write(vdbGrids);
154  vdbFile.close();
155 }
156 
157 int main(int argc, char* argv[]) {
158  if (argc != 2) {
159  std::cout << "Usage: ssftovdb parentDir" << std::endl;
160  return 0;
161  }
162  openvdb::initialize();
163 
164  VdbParams params;
165 
166  const Path directory(argv[1]);
167  std::set<Path> paths;
168  for (Path file : FileSystem::iterateDirectory(directory)) {
169  if (file.extension() != Path("ssf")) {
170  continue;
171  }
172  paths.insert(file);
173  }
174 
175  std::mutex mutex;
176  ThreadPool pool;
177  for (Path file : paths) {
178  pool.submit([&params, &mutex, file] {
179  {
180  std::unique_lock<std::mutex> lock(mutex);
181  std::cout << "Processing: " << file.native() << std::endl;
182  }
183 
184  convert(file, params);
185  });
186  }
187 
188  pool.waitForAll();
189 
190  openvdb::uninitialize();
191  return 0;
192 }
INLINE bool isReal(const AntisymmetricTensor &t)
Object representing a three-dimensional axis-aligned box.
uint32_t Size
Integral type used to index arrays (by default).
Definition: Globals.h:16
double Float
Precision used withing the code. Use Float instead of float or double where precision is important.
Definition: Globals.h:13
Three-dimensional dynamically-allocated container.
Base class for all particle materials.
Vectorized computations with integral numbers.
SPH kernels.
constexpr INLINE T max(const T &f1, const T &f2)
Definition: MathBasic.h:20
NAMESPACE_SPH_BEGIN constexpr INLINE T min(const T &f1, const T &f2)
Minimum & Maximum value.
Definition: MathBasic.h:15
INLINE auto floor(const T &f)
Definition: MathUtils.h:346
INLINE auto ceil(const T &f)
Definition: MathUtils.h:351
#define INLINE
Macros for conditional compilation based on selected compiler.
Definition: Object.h:31
Saving and loading particle data.
Simple thread pool with fixed number of threads.
@ POSITION
Positions (velocities, accelerations) of particles, always a vector quantity,.
@ ENERGY
Specific internal energy, always a scalar quantity.
@ MASS
Paricles masses, always a scalar quantity.
int main(int argc, char *argv[])
Definition: SsfToVdb.cpp:157
Tuple< Indices, Indices > getParticleBox(const Vector &r, const VdbParams &params)
Definition: SsfToVdb.cpp:47
Vector worldToRelative(const Vector &r, const VdbParams &params)
Definition: SsfToVdb.cpp:39
INLINE openvdb::Vec3R vectorToVec3R(const Vector &v)
Definition: SsfToVdb.cpp:26
void convert(const Path &path, const VdbParams params)
Definition: SsfToVdb.cpp:55
Storage loadSsf(const Path &path)
Definition: SsfToVdb.cpp:18
Vector relativeToWorld(const Vector &r, const VdbParams &params)
Definition: SsfToVdb.cpp:43
Statistics gathered and periodically displayed during the run.
Measuring time intervals and executing periodic events.
INLINE Tuple< TArgs &... > tieToTuple(TArgs &... args)
Creates a tuple of l-value references. Use IGNORE placeholder to omit one or more parameters.
Definition: Tuple.h:304
BasicVector< Float > Vector
Definition: Vector.h:539
@ H
Definition: Vector.h:25
@ Y
Definition: Vector.h:23
@ X
Definition: Vector.h:22
@ Z
Definition: Vector.h:24
Object providing safe access to continuous memory of data.
Definition: ArrayView.h:17
INLINE TCounter size() const
Definition: ArrayView.h:101
Input for the binary file, generated by BinaryOutput.
Definition: Output.h:352
virtual Outcome load(const Path &path, Storage &storage, Statistics &stats) override
Loads data from the file into the storage.
Definition: Output.cpp:718
Helper object defining three-dimensional interval (box).
Definition: Box.h:17
INLINE const Vector & lower() const
Returns lower bounds of the box.
Definition: Box.h:82
INLINE Vector size() const
Returns box dimensions.
Definition: Box.h:106
Helper object for storing three (possibly four) int or bool values.
Definition: Indices.h:16
INLINE Float value(const Vector &r, const Float h) const noexcept
Definition: Kernel.h:26
Object representing a path on a filesystem.
Definition: Path.h:17
Path & replaceExtension(const std::string &newExtension)
Changes the extension of the file.
Definition: Path.cpp:76
std::string native() const
Returns the native version of the path.
Definition: Path.cpp:71
static const Settings & getDefaults()
\brief Returns a reference to object containing default values of all settings.
void iterate(const TFunctor &functor)
Definition: Grid.h:223
Object holding various statistics about current run.
Definition: Statistics.h:22
Container storing all quantities used within the simulations.
Definition: Storage.h:230
MaterialView getMaterial(const Size matIdx) const
Returns an object containing a reference to given material.
Definition: Storage.cpp:366
Array< TValue > & getValue(const QuantityId key)
Retrieves a quantity values from the storage, given its key and value type.
Definition: Storage.cpp:191
Thread pool capable of executing tasks concurrently.
Definition: Pool.h:70
virtual SharedPtr< ITask > submit(const Function< void()> &task) override
Submits a task into the thread pool.
Definition: Pool.cpp:157
void waitForAll()
Blocks until all submitted tasks has been finished.
Definition: Pool.cpp:187
Heterogeneous container capable of storing a fixed number of values.
Definition: Tuple.h:146
Creating code components based on values from settings.
@ TILLOTSON_ENERGY_IV
Specific energy of incipient vaporization.
DirectoryAdapter iterateDirectory(const Path &directory)
Definition: FileSystem.cpp:338
Definition: MemoryPool.h:5
Float surfaceLevel
Definition: SsfToVdb.cpp:36
Indices gridDims
Definition: SsfToVdb.cpp:34