AGX Dynamics  2.35.0.1
agxPython/ScriptManager.h
Go to the documentation of this file.
1 /*
2 Copyright 2007-2022. 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 
20 #include <agx/config/AGX_USE_PYTHON.h>
21 #include <agx/config/AGX_USE_WEBSOCKETS.h>
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 
66  enum ScriptContextType
67  {
68  SCRIPTCONTEXT_INVALID = 0,
69  SCRIPTCONTEXT_PYTHON,
70  SCRIPTCONTEXT_AGXVIEWER,
71  SCRIPTCONTEXT_FMI,
72  SCRIPTCONTEXT_QTVIEWER
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()
106  AGX_DECLARE_POINTER_TYPES(StartPlaybackSignalCallback);
107  class AGXPYTHON_EXPORT StartPlaybackSignalCallback : public agxSDK::CallbackWrapper_Real
108  {
109  public:
110  StartPlaybackSignalCallback() : agxSDK::CallbackWrapper_Real() {}
111 
112  protected:
113 
114  virtual ~StartPlaybackSignalCallback() {}
115 
116  private:
117  void callback(agxSDK::SimulationController*, agx::Real value) override;
118  };
119 
120  AGX_DECLARE_POINTER_TYPES(StartRecordingSignalCallback);
121  class AGXPYTHON_EXPORT StartRecordingSignalCallback : public agxSDK::CallbackWrapper_Real
122  {
123  public:
124  StartRecordingSignalCallback() : agxSDK::CallbackWrapper_Real() {}
125 
126  protected:
127 
128  virtual ~StartRecordingSignalCallback() {}
129 
130  private:
131  void callback(agxSDK::SimulationController*, agx::Real value) override;
132  };
133 
134  AGX_DECLARE_POINTER_TYPES(StopPlaybackSignalCallback);
135  class AGXPYTHON_EXPORT StopPlaybackSignalCallback : public agxSDK::CallbackWrapper_Real
136  {
137  public:
138  StopPlaybackSignalCallback() : agxSDK::CallbackWrapper_Real() {}
139 
140  protected:
141 
142  virtual ~StopPlaybackSignalCallback() {}
143 
144  private:
145  void callback(agxSDK::SimulationController*, agx::Real value) override;
146  };
147 
148  AGX_DECLARE_POINTER_TYPES(StopRecordingSignalCallback);
149  class AGXPYTHON_EXPORT StopRecordingSignalCallback : public agxSDK::CallbackWrapper_Real
150  {
151  public:
152  StopRecordingSignalCallback() : agxSDK::CallbackWrapper_Real() {}
153 
154  protected:
155 
156  virtual ~StopRecordingSignalCallback() {}
157 
158  private:
159  void callback(agxSDK::SimulationController*, agx::Real value) override;
160  };
161 #endif
162 
163  class ReactiveScript;
164  class ScriptContext;
165 
170  class AGXPYTHON_EXPORT ScriptManager : public agx::Singleton
171  {
172 
173  public:
174 
175  friend class ReactiveInitializer;
176 
180  static ScriptContext* getContext();
181 
182  static bool hasInstance();
183  static bool isStartedFromExternalPython();
184 
189  static ScriptManager* instance(const std::string& requestor = "", const std::string& pythonPaths="", const std::string& pythonHome="", bool ignoreEnvironment = false);
190 
192  void shutdown() override;
193 
198  void registerError(const std::string& prefix = "");
199 
203  bool breakFlag();
204 
208  void reportError(const std::string& errorReport) const;
209 
216  bool addSearchPath(const agx::String& path);
217 
231  bool registerReactiveScript(ReactiveScript* script);
232  bool unregisterReactiveScript(const agx::Uuid& uuid);
233  bool isRegisteredReactiveScript(const agx::Uuid& uuid) const;
234  void clearReactiveScripts();
235  void acquireReactiveScriptContext(const agx::Uuid& scriptId, const char* func);
236  void releaseReactiveScriptContext(const agx::Uuid& scriptId, bool unlock = true);
237  void addScriptToSimulation(const agx::Uuid& scriptId, agxSDK::Simulation* simulation);
238 
239 #if AGX_USE_WEBSOCKETS()
240  void updateReactiveScripts(agxSDK::SimulationController* simulationController);
241 #endif
242  void updateReactiveScripts();
243 
244  void onStartPlaybackReactiveScripts(agx::Real value);
245  void onStartRecordingReactiveScripts(agx::Real value);
246  void onStopPlaybackReactiveScripts(agx::Real value);
247  void onStopRecordingReactiveScripts(agx::Real value);
248 
249 
254  std::string getLastErrorMessage() const;
255 
260  int getLastErrorLine() const;
261 
266  bool receivedErrorMessage() const;
267 
271  void resetError();
272 
276  void setLastErrorMessage(const std::string& errorMessage);
277  void setLastErrorLine(int line);
278 
286  ScriptIDERef requestVirtualIDE(const agx::Name& identifyingName);
287 
292  void setCurrentScriptSimulationOverride(agxSDK::Simulation* simulation);
293 
294 #if AGX_USE_WEBSOCKETS()
295  void registerSimulationControllerCallbacks(agxSDK::SimulationController* simulationController);
296  void unregisterSimulationControllerCallbacks(agxSDK::SimulationController* simulationController);
297 #endif
298 
299  // Destroy the main module for the given script.
300  void destroyMainModule(const agx::Uuid& scriptId);
301 
302 #if !defined(SWIGJAVA)
303 
304  void enableEmbeddedMode(const std::string& programName);
305 
307  void init(const std::string& pythonPaths="");
308 
310  void reset();
311 
314  agxPython::ScriptContextInterface *initScriptContext(agxPython::ScriptContextType contextType);
315 
318  agxPython::ScriptContextInterface* getScriptContext();
319 
320  // Create a separate main module for the given script.
321  void createMainModule(const agx::Uuid& scriptId);
322 
323  // Swap to the main module for the given script.
324  void swapMainModule(const agx::Uuid& scriptId);
325 
326  // Swap to the global main module.
327  void restoreGlobalMainModule(bool unlock = true);
328 
329  bool hasMainModule(const agx::Uuid& uuid) const;
330 
331  void* getMainModule();
332 
338  bool hasReactiveScriptErrors( bool printWarnings = true );
339 
346  bool doFile(const std::string& path, bool resolvePath = true);
347 
353  bool doString(const std::string& code, const std::string& origin);
354 
355 
362  bool doCompiledScript(void* compiled);
363  void* doCompiledFunction(void* funcObject, void **args, int numArgs);
364 
371  bool doFunction(const std::string& function, void* args = nullptr);
372 
373 
374 
375  agxSDK::Simulation* getCurrentScriptSimulation();
376 
377 #if AGX_USE_WEBSOCKETS()
378  agxSDK::SimulationController* getCurrentScriptSimulationController();
379 #endif
380 
381 
387  bool hasFunction(const std::string& function);
388 
389  bool getTreatInvalidAsErrors() const;
390  void setTreatInvalidAsErrors(const bool treatInvalidAsErrors);
391 
392 
410  void* getGlobals();
411 
415  std::string getProgramName();
416 
417 
418  protected:
419 
420  typedef std::map<std::string, std::string> PythonDefMap;
421 
422  PythonDefMap dumpGlobals(void* globals, std::ostream* logStream = nullptr);
423 
424 #endif
425 
426  public:
427 
429  static void startProfiling(void* obj, const char* decl);
431  static void endProfiling(void* obj, const char* decl);
433  static void abortProfiling(void* obj, const char* decl);
434 
435 
436  private:
437 
438  SINGLETON_CLASSNAME_METHOD();
439 
441  virtual ~ScriptManager();
442 
444  ScriptManager(const std::string& program, const std::string& pythonPaths, const std::string& pythonHome, bool ignoreEnvironment);
445 
446  agx::ref_ptr<ScriptContext> m_scriptContext;
447 
448  std::map<agx::Uuid, agx::ref_ptr<ReactiveScript> > m_reactiveScripts;
449  std::map<agx::Uuid, void*> m_reactiveScriptMainModules;
450 
451  void* m_globalMainModule;
452  void* m_currentMainModule;
453  ReactiveScript* m_currentReactiveScriptContext;
454 
455  agxSDK::Simulation* m_currentScriptSimulationOverride;
456 
457  bool m_initialized;
458  bool m_breakFlag;
459  std::string m_programName;
460  std::set<std::string> m_pythonPath;
461  wchar_t* m_pythonHome;
462  bool m_shutdownInProgress;
463  bool m_treatInvalidAsErrors;
464  std::string m_lastErrorMessage;
465  int m_lastErrorLine;
466  std::string m_scriptPath;
467  bool m_ignoreEnvironment;
468 
469  agx::Vector<ScriptIDERef> m_ideInstances;
470 
471 
472 #if AGX_USE_WEBSOCKETS()
473  StartPlaybackSignalCallbackRef m_startPlaybackSignalCallback;
474  StartRecordingSignalCallbackRef m_startRecordingSignalCallback;
475  StopPlaybackSignalCallbackRef m_stopPlaybackSignalCallback;
476  StopRecordingSignalCallbackRef m_stopRecordingSignalCallback;
477 
478 
479  agxSDK::SimulationController* m_simulationController;
480 #endif
481 
482  agx::ReentrantMutex m_mutex;
483 
484  static ScriptManager* s_instance;
485 
489  const char* const MOMENTUM_PROGRAM_NAME = "AlgoryxMomentum";
490 
491  friend class ScriptIDEAutocompleteCollection;
492 
493  };
494 
495  AGXPYTHON_EXPORT ScriptContext* getContext();
496 
497  AGXPYTHON_EXPORT bool scriptIsAttached();
498 
499  AGXPYTHON_EXPORT bool doFile(const std::string& path);
500 
501 } // namespace agxPython
502 
503 
504 #define g_pythonScriptManager agxPython::ScriptManager::instance("")
505 #define g_pythonScriptManagerForProgram(PROGRAM) agxPython::ScriptManager::instance(PROGRAM)
506 #define AGXPYTHON_REPORT_ERROR(errorMessage) \
507  if (g_pythonScriptManager->getTreatInvalidAsErrors() || agxUnit::isUnittestingEnabled()) \
508  { \
509  LOGGER_ERROR() << (errorMessage) << std::endl << LOGGER_END(); \
510  } \
511  else \
512  { \
513  LOGGER_WARNING() << (errorMessage) << std::endl << LOGGER_END(); \
514  }
515 
516 
517 #endif
518 
519 #ifdef _MSC_VER
520 # pragma warning(pop)
521 #endif
522 
523 #endif
#define AGX_DECLARE_POINTER_TYPES(type)
Definition: Referenced.h:248
#define AGXPYTHON_EXPORT
Simulation is a class that bridges the collision space agxCollide::Space and the dynamic simulation s...
Definition: Simulation.h:127
Representation of a name string.
Definition: Name.h:33
Base class for Singletons that should have its shutdown called explicitly before exit of the applicat...
Definition: Singleton.h:31
A UUID, or Universally unique identifier, is intended to uniquely identify information in a distribut...
Definition: Uuid.h:42
Templated vector class.
Definition: agx/Vector.h:53
Smart pointer for handling referenced counted objects.
Definition: ref_ptr.h:30
#define AGX_NOEXCEPT
Definition: macros.h:46
The agxSDK namespace contain classes to bridge the collision detection system and the dynamical simul...
Definition: Constraint.h:31
double Real
Definition: Real.h:42
void AGXPHYSICS_EXPORT shutdown()
Shutdown agx.
std::recursive_mutex ReentrantMutex
Definition: Object.h:49
void AGXPHYSICS_EXPORT init()
Initialize agx.