SPH
Launcher.cpp
Go to the documentation of this file.
1 
3 #include "Sph.h"
4 #include "run/Config.h"
5 #include "run/Node.h"
6 #include "run/SpecialEntries.h"
9 #include "run/jobs/IoJobs.h"
10 #include "run/jobs/MaterialJobs.h"
11 #include "run/jobs/ParticleJobs.h"
12 #include "run/jobs/ScriptJobs.h"
14 
15 using namespace Sph;
16 
17 static Array<ArgDesc> params{
18  { "p", "project", ArgEnum::STRING, "Path to the project file." },
19  { "n", "node", ArgEnum::STRING, "Name of the node to evaluate" },
20 };
21 
22 static void printBanner(ILogger& logger) {
23  logger.write("*******************************************************************************");
24  logger.write("******************************** OpenSPH CLI **********************************");
25  logger.write("*******************************************************************************");
26 }
27 
30 private:
31  ConfigNode& input;
32  ILogger& logger;
33 
34 public:
35  LoadProc(ConfigNode& input, ILogger& logger)
36  : input(input)
37  , logger(logger) {}
38 
39  virtual void onCategory(const std::string& UNUSED(name)) const override {}
40 
41  virtual void onEntry(const std::string& name, IVirtualEntry& entry) const override {
42  const IVirtualEntry::Type type = entry.getType();
43 
44  try {
45  switch (type) {
47  entry.set(input.get<bool>(name));
48  break;
50  entry.set(input.get<int>(name));
51  break;
53  entry.set(input.get<Float>(name));
54  break;
56  entry.set(input.get<Interval>(name));
57  break;
59  entry.set(input.get<Vector>(name));
60  break;
62  entry.set(input.get<std::string>(name));
63  break;
65  entry.set(input.get<Path>(name));
66  break;
69  EnumWrapper ew = entry.get();
70  ew.value = input.get<int>(name);
71  entry.set(ew);
72  break;
73  }
76  ExtraEntry extra(makeAuto<CurveEntry>());
77  extra.fromString(input.get<std::string>(name));
78  entry.set(extra);
79  break;
80  }
81  default:
83  }
84  } catch (const Exception& e) {
85  logger.write("Failed to load value, keeping the default.\n", e.what());
86  }
87  }
88 };
89 
91 static void registerJobs() {
92  static SphJob sSph("");
93  static CollisionGeometrySetup sSetup("");
94  static MonolithicBodyIc sIc("");
95  static SaveFileJob sIo("");
96  static BlockJob sBlock("");
97  static MaterialJob sMat("");
98 
99 #ifdef SPH_USE_CHAISCRIPT
100  static ChaiScriptJob sScript("");
101 #endif
102 }
103 
104 static void run(const ArgParser& parser, ILogger& logger) {
105 #ifdef SPH_VERSION
106  logger.write("Running opensph-cli (version ", SPH_STR(SPH_VERSION), ")");
107 #else
108  logger.write("Running opensph-cli (unknown version)");
109 #endif
110  const Path projectPath(parser.getArg<std::string>("p"));
111  const std::string nodeToRun(parser.getArg<std::string>("n"));
112 
113  Config config;
114  config.load(projectPath);
115 
117 
118  SharedPtr<ConfigNode> inNodes = config.getNode("nodes");
119  // lists node connections: node, target slot and target node
120  Array<Tuple<SharedPtr<JobNode>, std::string, std::string>> allToConnect;
121 
122  inNodes->enumerateChildren([&nodes, &allToConnect, &logger](std::string name, ConfigNode& input) {
123  const std::string className = input.get<std::string>("class_name");
124  RawPtr<IJobDesc> desc = getJobDesc(className);
125  if (!desc) {
126  throw Exception("Cannot find desc for node '" + className + "'");
127  }
128 
129  AutoPtr<IJob> job = desc->create(name);
130  SharedPtr<JobNode> node = makeShared<JobNode>(std::move(job));
131  nodes.insert(name, node);
132 
133  VirtualSettings settings = node->getSettings();
134  settings.enumerate(LoadProc(input, logger));
135 
136  for (Size i = 0; i < node->getSlotCnt(); ++i) {
137  const std::string slotName = node->getSlot(i).name;
138  Optional<std::string> connectedName = input.tryGet<std::string>(slotName);
139  if (connectedName) {
140  allToConnect.push(makeTuple(node, slotName, connectedName.value()));
141  }
142  }
143  });
144 
145  for (auto& toConnect : allToConnect) {
146  for (auto& element : nodes) {
147  if (element.key == toConnect.get<2>()) {
148  element.value->connect(toConnect.get<0>(), toConnect.get<1>());
149  }
150  }
151  }
152 
153  Optional<SharedPtr<JobNode>&> runner = nodes.tryGet(nodeToRun);
154  if (!runner) {
155  throw Exception("No node '" + nodeToRun + "' found in the project");
156  }
157 
158  logger.write("Running node tree:");
159  runner.value()->enumerate([&logger](SharedPtr<JobNode> node, const Size depth) {
160  logger.write(std::string(depth * 3, ' '), " - ", node->instanceName());
161  });
162 
164  RunSettings globals = EMPTY_SETTINGS;
168  globals.set(RunSettingsId::RUN_RNG_SEED, 1234);
170  globals.set(RunSettingsId::GENERATE_UVWS, false);
171  NullJobCallbacks callbacks;
172  runner.value()->run(globals, callbacks);
173 }
174 
175 int main(int argc, char* argv[]) {
176  StdOutLogger logger;
177  registerJobs();
178 
179  try {
180  ArgParser parser(params);
181  parser.parse(argc, argv);
182 
183  run(parser, logger);
184 
185  return 0;
186 
187  } catch (HelpException& e) {
188  printBanner(logger);
189  logger.write(e.what());
190  return 0;
191  } catch (const Exception& e) {
192  logger.write("Run failed!\n", e.what());
193  return -1;
194  }
195 }
#define SPH_STR(x)
Definition: Assert.h:119
#define NOT_IMPLEMENTED
Helper macro marking missing implementation.
Definition: Assert.h:100
Interface for the configuration files storing job data.
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
RawPtr< IJobDesc > getJobDesc(const std::string &name)
Returns a job descriptor for given class name.
Definition: Job.cpp:34
int main(int argc, char *argv[])
Definition: Launcher.cpp:175
#define UNUSED(x)
Definition: Object.h:37
Additional bindings to IVirtualSettings.
Includes common headers.
INLINE auto makeTuple(TArgs &&... args)
Creates a tuple from a pack of values, utilizing type deduction.
Definition: Tuple.h:298
Provides functions for parsing command-line arguments.
Definition: ArgsParser.h:62
void parse(const int argc, char **argv)
Parses the input arguments and stored the parsed values.
Definition: ArgsParser.cpp:16
TValue getArg(const std::string &name) const
Returns the value of an argument, given its short name (without the dash).
Definition: ArgsParser.h:95
INLINE void push(U &&u)
Adds new element to the end of the array, resizing the array if necessary.
Definition: Array.h:306
Represents a single node in the hierarchy written into config file.
Definition: Config.h:198
Optional< Type > tryGet(const std::string &name)
Tries to return a value stored in the node.
Definition: Config.h:232
Type get(const std::string &name)
Returns a value stored in the node.
Definition: Config.h:220
Provides functionality for reading and writing configuration files.
Definition: Config.h:272
SharedPtr< ConfigNode > getNode(const std::string &name)
Returns a node with given name.
Definition: Config.cpp:85
void load(const Path &path)
Reads content of given file and deserializes the config from the loaded string.
Definition: Config.cpp:131
Generic exception.
Definition: Exceptions.h:10
virtual const char * what() const noexcept
Definition: Exceptions.h:18
Copyable wrapper of a IExtraEntry.
void fromString(const std::string &s) const
Container of key-value pairs.
Definition: FlatMap.h:19
INLINE TValue & insert(const TKey &key, const TValue &value)
Adds a new element into the map or sets new value of element with the same key.
Definition: FlatMap.h:65
Exception thrown when used passes -h or –help parameter.
Definition: ArgsParser.h:32
Interface providing generic (text, human readable) output of the program.
Definition: Logger.h:22
void write(TArgs &&... args)
Creates and logs a message by concatenating arguments.
Definition: Logger.h:37
Represents a virtual entry in the settings.
virtual bool set(const Value &value)=0
Modifies the current value of the entry.
virtual Value get() const =0
Returns the currently stored value.
virtual Type getType() const =0
Returns the type of this entry.
Object representing a 1D interval of real numbers.
Definition: Interval.h:17
Size getSlotCnt() const
Returns the number of provider slots of this node.
Definition: Node.cpp:132
std::string instanceName() const
Returns the instance name of the job.
Definition: Node.cpp:14
SlotData getSlot(const Size index) const
Returns the information about given slot.
Definition: Node.cpp:136
VirtualSettings getSettings() const
Returns settings object allowing to access and modify the state of the job.
Definition: Node.cpp:39
virtual void onCategory(const std::string &UNUSED(name)) const override
Definition: Launcher.cpp:39
LoadProc(ConfigNode &input, ILogger &logger)
Definition: Launcher.cpp:35
virtual void onEntry(const std::string &name, IVirtualEntry &entry) const override
Called for every entry in the current category.
Definition: Launcher.cpp:41
Creates a single monolithic body.
INLINE Type & value()
Returns the reference to the stored value.
Definition: Optional.h:172
Object representing a path on a filesystem.
Definition: Path.h:17
Non-owning wrapper of pointer.
Definition: RawPtr.h:19
Settings & set(const TEnum idx, TValue &&value, std::enable_if_t<!std::is_enum< std::decay_t< TValue >>::value, int >=0)
Saves a value into the settings.
Definition: Settings.h:226
Standard output logger.
Definition: Logger.h:138
Interface allowing to enumerate all entries in the settings.
Holds a map of virtual entries, associated with a unique name.
void enumerate(const IEntryProc &proc)
Enumerates all entries stored in the settings.
@ UNIFORM
Mersenne Twister PRNG from Standard library.
const EmptySettingsTag EMPTY_SETTINGS
Definition: Settings.h:32
@ CUBIC_SPLINE
M4 B-spline (piecewise cubic polynomial)
@ SPH_KERNEL
Index of SPH Kernel, see KernelEnum.
@ GENERATE_UVWS
If true, the mapping coordinates will be computed and saved for all bodies in the simulation.
@ RUN_THREAD_CNT
Number of threads used by the code. If 0, all available threads are used.
@ RUN_RNG
Selected random-number generator used within the run.
@ RUN_RNG_SEED
Seed for the random-number generator.
Definition: MemoryPool.h:5
Wrapper of an enum.
Definition: Settings.h:37
int value
Definition: Settings.h:38
std::string name
Identifier of the slot, used by the job to obtain the provided data.
Definition: Node.h:60