AGXDynamics  2.31.1.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
agxPython/ScriptManager.h
Go to the documentation of this file.
1 /*
2 Copyright 2007-2021. Algoryx Simulation AB.
3 
4 All AGX source code, intellectual property, documentation, sample code,
5 tutorials, scene files and technical white papers, are copyrighted, proprietary
6 and confidential material of Algoryx Simulation AB. You may not download, read,
7 store, distribute, publish, copy or otherwise disseminate, use or expose this
8 material unless having a written signed agreement with Algoryx Simulation AB, or having been
9 advised so by Algoryx Simulation AB for a time limited evaluation, or having purchased a
10 valid commercial license from Algoryx Simulation AB.
11 
12 Algoryx Simulation AB disclaims all responsibilities for loss or damage caused
13 from using this software, unless otherwise stated in written agreements with
14 Algoryx Simulation AB.
15 */
16 
17 #ifndef AGXPYTHON_SCRIPTMANAGER_H
18 #define AGXPYTHON_SCRIPTMANAGER_H
19 
22 #include <agx/config.h>
23 
24 #if AGX_USE_PYTHON()
25 
26 #include <agx/ref_ptr.h>
27 #include <agxPython/export.h>
28 
29 #include <agx/Referenced.h>
30 #include <agx/Logger.h>
31 #include <agx/Timer.h>
32 #include <agx/agx_vector_types.h>
33 #include <agx/Uuid.h>
34 
35 #if AGX_USE_WEBSOCKETS()
37 #endif
38 
41 
42 
43 #ifdef _MSC_VER
44 # include <agx/Windows.h>
45 # pragma warning( push )
46 # pragma warning( disable: 4512 ) // Disable warning about assignment operator could not be generated due to reference members.
47 # pragma warning( disable: 4275 ) // Disable non dll-interface class std::exception used as base for dll-interface class agxPython::ScriptError
48 # endif
49 
50 #include <agxPython/ScriptIDE.h>
51 
52 #include <string>
53 #include <map>
54 #include <set>
55 #include <exception>
56 
57 #if AGX_USE_WEBSOCKETS()
58 namespace agxSDK
59 {
60  class SimulationController;
61 }
62 #endif
63 
64 namespace agxPython {
65 
67  {
73  };
74 
85  class AGXPYTHON_EXPORT ScriptError : public std::exception
86  {
87 
88  public:
89 
90  ScriptError();
91  ScriptError(const ScriptError& other);
92  ScriptError(std::string scriptError, std::string scriptFile);
93 
94  virtual ~ScriptError();
95 
96  virtual const char* what() const AGX_NOEXCEPT override; //=0;
97 
98  private:
99 
100  std::string m_msg;
101 
102  };
103 
104 
105 #if AGX_USE_WEBSOCKETS()
108  {
109  public:
110  StartPlaybackSignalCallback() : agxSDK::CallbackWrapper_Real() {}
111 
112  protected:
113 
115 
116  private:
117  void callback(agxSDK::SimulationController*, agx::Real value) override;
118  };
119 
122  {
123  public:
124  StartRecordingSignalCallback() : agxSDK::CallbackWrapper_Real() {}
125 
126  protected:
127 
129 
130  private:
131  void callback(agxSDK::SimulationController*, agx::Real value) override;
132  };
133 
136  {
137  public:
138  StopPlaybackSignalCallback() : agxSDK::CallbackWrapper_Real() {}
139 
140  protected:
141 
143 
144  private:
145  void callback(agxSDK::SimulationController*, agx::Real value) override;
146  };
147 
150  {
151  public:
152  StopRecordingSignalCallback() : agxSDK::CallbackWrapper_Real() {}
153 
154  protected:
155 
157 
158  private:
159  void callback(agxSDK::SimulationController*, agx::Real value) override;
160  };
161 #endif
162 
163  class ReactiveScript;
164  class ScriptContext;
165 
171  {
172 
173  public:
174 
175  friend class ReactiveInitializer;
176 
180  static ScriptContext* getContext();
181 
182  static bool hasInstance();
183 
188  static ScriptManager* instance(const std::string& requestor = "", const std::string& pythonPaths="", const std::string& pythonHome="", bool ignoreEnvironment = false);
189 
191  void shutdown() override;
192 
197  void registerError(const std::string& prefix = "");
198 
202  bool breakFlag();
203 
207  void reportError(const std::string& errorReport) const;
208 
215  bool addSearchPath(const agx::String& path);
216 
230  bool registerReactiveScript(ReactiveScript* script);
231  bool unregisterReactiveScript(const agx::Uuid& uuid);
232  bool isRegisteredReactiveScript(const agx::Uuid& uuid) const;
233  void clearReactiveScripts();
234  void acquireReactiveScriptContext(const agx::Uuid& scriptId, const char* func);
235  void releaseReactiveScriptContext(const agx::Uuid& scriptId, bool unlock = true);
236  void addScriptToSimulation(const agx::Uuid& scriptId, agxSDK::Simulation* simulation);
237 
238 #if AGX_USE_WEBSOCKETS()
239  void updateReactiveScripts(agxSDK::SimulationController* simulationController);
240 #endif
241  void updateReactiveScripts();
242 
243  void onStartPlaybackReactiveScripts(agx::Real value);
244  void onStartRecordingReactiveScripts(agx::Real value);
245  void onStopPlaybackReactiveScripts(agx::Real value);
246  void onStopRecordingReactiveScripts(agx::Real value);
247 
248 
253  std::string getLastErrorMessage() const;
254 
259  int getLastErrorLine() const;
260 
265  bool receivedErrorMessage() const;
266 
270  void resetError();
271 
275  void setLastErrorMessage(const std::string& errorMessage);
276  void setLastErrorLine(int line);
277 
285  ScriptIDERef requestVirtualIDE(const agx::Name& identifyingName);
286 
291  void setCurrentScriptSimulationOverride(agxSDK::Simulation* simulation);
292 
293 #if AGX_USE_WEBSOCKETS()
294  void registerSimulationControllerCallbacks(agxSDK::SimulationController* simulationController);
295  void unregisterSimulationControllerCallbacks(agxSDK::SimulationController* simulationController);
296 #endif
297 
298  // Destroy the main module for the given script.
299  void destroyMainModule(const agx::Uuid& scriptId);
300 
301 #if !defined(SWIGJAVA)
302 
303  void enableEmbeddedMode(const std::string& programName);
304 
306  void init(const std::string& pythonPaths="");
307 
309  void reset();
310 
313  agxPython::ScriptContextInterface *initScriptContext(agxPython::ScriptContextType contextType);
314 
317  agxPython::ScriptContextInterface* getScriptContext();
318 
319  // Create a separate main module for the given script.
320  void createMainModule(const agx::Uuid& scriptId);
321 
322  // Swap to the main module for the given script.
323  void swapMainModule(const agx::Uuid& scriptId);
324 
325  // Swap to the global main module.
326  void restoreGlobalMainModule(bool unlock = true);
327 
328  bool hasMainModule(const agx::Uuid& uuid) const;
329 
330  void* getMainModule();
331 
337  bool hasReactiveScriptErrors( bool printWarnings = true );
338 
344  bool doFile(const std::string& path);
345 
351  bool doString(const std::string& code, const std::string& origin);
352 
353 
360  bool doCompiledScript(void* compiled);
361  void* doCompiledFunction(void* funcObject, void **args, int numArgs);
362 
369  bool doFunction(const std::string& function, void* args = nullptr);
370 
371 
372 
373  agxSDK::Simulation* getCurrentScriptSimulation();
374 
375 #if AGX_USE_WEBSOCKETS()
376  agxSDK::SimulationController* getCurrentScriptSimulationController();
377 #endif
378 
379 
385  bool hasFunction(const std::string& function);
386 
387  bool getTreatInvalidAsErrors() const;
388  void setTreatInvalidAsErrors(const bool treatInvalidAsErrors);
389 
390 
408  void* getGlobals();
409 
413  std::string getProgramName();
414 
415 
416  protected:
417 
418  typedef std::map<std::string, std::string> PythonDefMap;
419 
420  PythonDefMap dumpGlobals(void* globals, std::ostream* logStream = nullptr);
421 
422 #endif
423 
424  public:
425 
427  static void startProfiling(void* obj, const char* decl);
429  static void endProfiling(void* obj, const char* decl);
431  static void abortProfiling(void* obj, const char* decl);
432 
433 
434  private:
435 
436  SINGLETON_CLASSNAME_METHOD();
437 
439  virtual ~ScriptManager();
440 
442  ScriptManager(const std::string& program, const std::string& pythonPaths, const std::string& pythonHome, bool ignoreEnvironment);
443 
444  agx::ref_ptr<ScriptContext> m_scriptContext;
445 
446  std::map<agx::Uuid, agx::ref_ptr<ReactiveScript> > m_reactiveScripts;
447  std::map<agx::Uuid, void*> m_reactiveScriptMainModules;
448 
449  void* m_globalMainModule;
450  void* m_currentMainModule;
451  ReactiveScript* m_currentReactiveScriptContext;
452 
453  agxSDK::Simulation* m_currentScriptSimulationOverride;
454 
455  bool m_initialized;
456  bool m_breakFlag;
457  std::string m_programName;
458  std::set<std::string> m_pythonPath;
459  wchar_t* m_pythonHome;
460  bool m_shutdownInProgress;
461  bool m_treatInvalidAsErrors;
462  std::string m_lastErrorMessage;
463  int m_lastErrorLine;
464  std::string m_scriptPath;
465  bool m_ignoreEnvironment;
466 
467  agx::Vector<ScriptIDERef> m_ideInstances;
468 
469 
470 #if AGX_USE_WEBSOCKETS()
471  StartPlaybackSignalCallbackRef m_startPlaybackSignalCallback;
472  StartRecordingSignalCallbackRef m_startRecordingSignalCallback;
473  StopPlaybackSignalCallbackRef m_stopPlaybackSignalCallback;
474  StopRecordingSignalCallbackRef m_stopRecordingSignalCallback;
475 
476 
477  agxSDK::SimulationController* m_simulationController;
478 #endif
479 
480  agx::Mutex m_mutex;
481 
482  static ScriptManager* s_instance;
483 
487  const char* const MOMENTUM_PROGRAM_NAME = "AlgoryxMomentum";
488 
490 
491  };
492 
494 
496 
497  AGXPYTHON_EXPORT bool doFile(const std::string& path);
498 
499 } // namespace agxPython
500 
501 
502 #define g_pythonScriptManager agxPython::ScriptManager::instance("")
503 #define g_pythonScriptManagerForProgram(PROGRAM) agxPython::ScriptManager::instance(PROGRAM)
504 #define AGXPYTHON_REPORT_ERROR(errorMessage) \
505  if (g_pythonScriptManager->getTreatInvalidAsErrors() || agxUnit::isUnittestingEnabled()) \
506  { \
507  LOGGER_ERROR() << (errorMessage) << std::endl << LOGGER_END(); \
508  } \
509  else \
510  { \
511  LOGGER_WARNING() << (errorMessage) << std::endl << LOGGER_END(); \
512  }
513 
514 
515 #endif
516 
517 #ifdef _MSC_VER
518 # pragma warning(pop)
519 #endif
520 
521 #endif
void AGXPHYSICS_EXPORT init()
Initialize agx.
void AGXPHYSICS_EXPORT shutdown()
Shutdown agx.
Class that manages the embedded Python interpreter and a script context.
AGXPYTHON_EXPORT ScriptContext * getContext()
#define AGX_NOEXCEPT
Definition: Object.h:49
AGXLUA_EXPORT int doString(lua_State *L)
AGXPYTHON_EXPORT bool scriptIsAttached()
#define AGX_DECLARE_POINTER_TYPES(type)
Definition: Referenced.h:248
Representation of a name string.
Definition: Name.h:32
Internal class which interfaces to a ScriptContext in an abstract and safe manner.
std::map< std::string, std::string > PythonDefMap
The ReactiveScript class is derived from the agxSDK::StepEventListener class and require an agxSDK::S...
Exception base class for all fatal runtime errors caused by Python scripts.
Templated vector class.
Definition: Vector.h:52
Smart pointer for handling referenced counted objects.
Definition: ref_ptr.h:29
Class which manages a runtime bridge between a script and the Python ScriptManager.
AGXPYTHON_EXPORT bool doFile(const std::string &path)
A UUID, or Universally unique identifier, is intended to uniquely identify information in a distribut...
Definition: Uuid.h:41
std::mutex Mutex
Definition: Referenced.h:93
Simulation is a class that bridges the collision space agxCollide::Space and the dynamic simulation s...
Definition: Simulation.h:121
double Real
Definition: Real.h:42
#define AGXPYTHON_EXPORT
Base class for Singletons that should have its shutdown called explicitly before exit of the applicat...
Definition: Singleton.h:30