AGX Dynamics  2.35.0.1
agxLua/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 AGXLUA_SCRIPTMANAGER_H
18 #define AGXLUA_SCRIPTMANAGER_H
19 
20 #ifdef _MSC_VER
21 # pragma warning( push )
22 # pragma warning( disable: 4512 ) // Disable warning about assignment operator could not be generated due to reference members.
23 # endif
24 
25 
26 #include <agx/config/AGX_USE_LUA.h>
27 #include <agx/config.h>
28 
29 #if AGX_USE_LUA()
30 
31 #include <agx/ref_ptr.h>
32 #include <agx/DynamicLibrary.h>
33 #include <agxLua/export.h>
34 
35 
36 #include <agx/Referenced.h>
37 #include <agx/Logger.h>
38 #include <agx/Timer.h>
39 #include <agxLua/GarbageListener.h>
40 
41 extern "C" {
42 # include "lua.h"
43 # include "lualib.h"
44 # include "lauxlib.h"
45 }
46 
47 
48 
49 namespace agxSDK
50 {
51  class Simulation;
52 }
53 
54 namespace agxLua {
55 
56 #define LUA_SCRIPT_PLUGIN_VERSION "1.0"
57 
58  class AGXLUA_EXPORT ScriptManager : public agx::Singleton
59  {
60  public:
61 
62 
67  static ScriptManager* instance( bool erase=false );
68 
69 
70  class ScriptPlugin : public agx::Referenced
71  {
72  public:
73  friend class ScriptManager;
74 
79  ScriptPlugin() { m_script_mgr = agxLua::ScriptManager::instance(); }
80 
84  virtual std::string getName()=0;
85 
87  std::string getPluginVersion() { return LUA_SCRIPT_PLUGIN_VERSION; }
88 
93  void addDependentPlugin(const std::string pluginName )
94  {
95  m_dependentPlugins.push_back( pluginName );
96  }
97 
104  void registerDependentPlugins( void );
105 
107  virtual void init(lua_State* lua)=0;
108 
110  const StringVector& getDependentPlugins() const { return m_dependentPlugins; }
111 
112  protected:
113 
115  virtual void close()=0;
116 
117  // Destructor
118  virtual ~ScriptPlugin() {}
119  ScriptManager* m_script_mgr;
120 
121  StringVector m_dependentPlugins;
122 
123  };
124 
125 
126  template<class T>
128  class RegisterScriptPluginProxy
129  {
130  public:
131  RegisterScriptPluginProxy()
132  {
133  if (ScriptManager::instance())
134  {
135  m_plugin = new T;
136 
137  // Check so that the plugin version matches the one of the ScriptManager
138  if (m_plugin->getPluginVersion() != ScriptManager::instance()->getPluginVersion())
139  LOGGER_ERROR() <<
140  "Plugin version (" << m_plugin->getPluginVersion() <<
141  ") does not match required version (" <<
142  ScriptManager::instance()->getPluginVersion() << ")" << LOGGER_END();
143 
144  // Make sure that any plugins that this plugin depends on is initialized before.
145  ScriptPlugin::StringVector::const_iterator it = m_plugin->getDependentPlugins().begin();
146  for(; it != m_plugin->getDependentPlugins().end(); ++it)
147  {
148  if (!ScriptManager::instance()->requestScriptPlugin( *it ))
149  LOGGER_ERROR() << "Error loading plugin: " << *it << LOGGER_END();
150  }
151 
152  // Initialize the plugin
153  m_plugin->init( ScriptManager::instance()->getLua());
154 
155  // Add the plugin to the list of plugins at the script manager
156  ScriptManager::instance()->addScriptPlugin(m_plugin.get());
157  }
158  }
159 
160  ~RegisterScriptPluginProxy()
161  {
162  if (ScriptManager::instance())
163  {
164  // Unlist the plugin
165  ScriptManager::instance()->removeScriptPlugin(m_plugin.get());
166  }
167  }
168 
169 
170  agx::ref_ptr<T> getPlugin() { return m_plugin; }
171 
172  protected:
173  agx::ref_ptr<T> m_plugin;
174  };
175 
201  bool registerLuaEntry(const void* ptr, const char* functionName);//, const std::string& class_name);
202  bool unregisterLuaEntry(const void* ptr);//, const std::string& class_name);
203 
204 #define ScriptManager_REGISTER_OBJECT( P, NAME ) agxLua::ScriptManager::instance()->registerLuaEntry(P, NAME) //this, typeid(this).name())
205 #define ScriptManager_UNREGISTER_OBJECT( P ) agxLua::ScriptManager::instance()->unregisterLuaEntry(P) //this, typeid(this).name())
206 
208  void addScriptPlugin(ScriptPlugin *);
209 
211  void removeScriptPlugin(ScriptPlugin *);
212 
214  bool requestScriptPlugin(const std::string& libraryName);
215 
217  bool isLoaded(const std::string& libraryName);
218 
220  void shutdown() override;
221 
223  void setDebugMode(bool flag = true);
224 
226  void setLogPath(const std::string& path) { m_log_path=path; }
227 
229  void init(lua_State* L=nullptr, unsigned int stacksize=1024);
230 
232  lua_State* getLua() { return m_lua_state; }
233 
235  const char* getLogPath() { return m_log_path.c_str(); }
236 
238  bool doFile(const std::string& path);
239 
241  bool doString(const std::string& string);
242 
248  bool doGarbageCollection( agx::Real now = agx::Real(-1.0) );
249 
250  void setGarbageCollectionEnabled( bool b );
251  bool getGarbageCollectionEnabled() const { return m_garbage_collection_enabled; };
252 
253  void setGarbageCollectionFrequency( agx::Real f ) { m_garbage_collection_frequency = f; };
254  agx::Real getGarbageCollectionFrequency() const { return m_garbage_collection_frequency; };
255 
256  std::string getPluginVersion() { return m_plugin_version; }
257 
258  bool registerSimulation( agxSDK::Simulation* simulation );
259 
260  bool getTreatInvalidAsErrors() const {return m_treatInvalidAsErrors;}
261  void setTreatInvalidAsErrors(const bool treatInvalidAsErrors) {m_treatInvalidAsErrors = treatInvalidAsErrors;}
262 
264  int getMemoryUsed() const;
265 
266  std::string getLastErrorMessage() const { return m_lastErrorMessage; }
267  void setLastErrorMessage(const std::string& errorMessage) { m_lastErrorMessage = errorMessage; }
268  private:
269 
270  SINGLETON_CLASSNAME_METHOD();
271 
272  // Register various functions accessible from Lua.
273  void registerFunctions();
274 
275 
276  agx::ref_ptr<GarbageListener> m_garbageListener;
277  bool m_garbage_collection_enabled;
278  bool m_garbage_collection_requested;
279  agx::Real m_garbage_collection_frequency;
280  agx::Real m_last_garbage_collection;
281 
282  typedef agx::Vector< agx::ref_ptr<ScriptPlugin> > ScriptPluginVector;
283  typedef ScriptPluginVector::iterator ScriptPluginVectorIterator;
284 
285  ScriptPluginVector m_plugin_vector;
286 
287  typedef agx::Vector< agx::ref_ptr<agx::DynamicLibrary> > DynamicLibraryList;
288  bool closeLibrary(const std::string& fileName);
289 
291  std::string createLibraryNameForExtension(const std::string& ext);
292 
294  DynamicLibraryList::iterator getLibraryItr(const std::string& fileName);
295 
297  agx::DynamicLibrary* getLibrary(const std::string& fileName);
298 
299 
300  DynamicLibraryList m_dllist;
301 
302  std::string m_log_path;
303  lua_State* m_lua_state;
304 
306  virtual ~ScriptManager();
307 
309  ScriptManager( void );
310 
311  const std::string m_plugin_version;
312 
313 
314  typedef agx::HashTable<const void *,int> ObjectReferenceMap;
315  ObjectReferenceMap m_object_references;
316  bool m_initialized;
317  int m_maxMemSize;
318  int m_incrementalSize;
319  bool m_shutdownInProgress;
320  bool m_treatInvalidAsErrors;
321  std::string m_lastErrorMessage;
322 
323  static ScriptManager* s_instance;
324  };
325 
326 #define g_luaScriptManager agxLua::ScriptManager::instance()
327 
328 
329  class AGXLUA_EXPORT LuaCallback
330  {
331  public:
332  LuaCallback(void* self, const char* className) : m_self(self), m_lua(g_luaScriptManager->getLua())
333  {
334  ScriptManager_REGISTER_OBJECT(self, className);
335  }
336 
337  virtual ~LuaCallback()
338  {
339  ScriptManager_UNREGISTER_OBJECT(m_self);
340  }
341  protected:
342  void* m_self;
343  lua_State* m_lua;
344  };
345 
346 
347 } // namespace agxLua
348 
349 
350 
351 #if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__) || defined( __MWERKS__)
352 # if defined( AGX_LIBRARY_STATIC )
353 # define AGXLUAPLUGIN_EXPORT
354 # else
355 # define AGXLUAPLUGIN_EXPORT __declspec(dllexport)
356 # endif
357 #elif !defined(_MSC_VER)
358  // Non Win32
359  #if __GNUC__ >= 4
360  #define AGXLUAPLUGIN_EXPORT __attribute__ ((visibility("default")))
361  #else
362  #define AGXLUAPLUGIN_EXPORT
363  #endif
364 #else
365  #define AGXLUAPLUGIN_EXPORT
366 #endif
367 
368 
369 #endif
370 
371 #ifdef _MSC_VER
372 # pragma warning(pop)
373 #endif
374 
375 #endif
#define LOGGER_ERROR()
Definition: Logger.h:22
#define LOGGER_END()
Definition: Logger.h:26
#define AGXLUA_EXPORT
Definition: agxLua/export.h:42
Simulation is a class that bridges the collision space agxCollide::Space and the dynamic simulation s...
Definition: Simulation.h:127
Inheritance with partial specialization due to bug with ref_ptr containers.
Base class providing referencing counted objects.
Definition: Referenced.h:114
Base class for Singletons that should have its shutdown called explicitly before exit of the applicat...
Definition: Singleton.h:31
Smart pointer for handling referenced counted objects.
Definition: ref_ptr.h:30
The agxSDK namespace contain classes to bridge the collision detection system and the dynamical simul...
Definition: Constraint.h:31
Vector< AgXString< std::string > > StringVector
Definition: String.h:31
double Real
Definition: Real.h:42
LinearProbingHashSetImplementation< KeyT, HashT >::iterator end(LinearProbingHashSetImplementation< KeyT, HashT > &set)
void AGXPHYSICS_EXPORT shutdown()
Shutdown agx.
void AGXPHYSICS_EXPORT init()
Initialize agx.