LuaBinder.h 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #pragma once
  6. #include <AnKi/Script/Common.h>
  7. #include <AnKi/Util/Assert.h>
  8. #include <AnKi/Util/StdTypes.h>
  9. #include <AnKi/Util/Allocator.h>
  10. #include <AnKi/Util/String.h>
  11. #include <AnKi/Util/Functions.h>
  12. #include <AnKi/Util/HashMap.h>
  13. #include <Lua/lua.hpp>
  14. #ifndef ANKI_LUA_HPP
  15. # error "Wrong LUA header included"
  16. #endif
  17. namespace anki
  18. {
  19. // Forward
  20. class LuaUserData;
  21. class SceneGraph;
  22. class MainRenderer;
  23. /// @addtogroup script
  24. /// @{
  25. /// @memberof LuaUserData
  26. using LuaUserDataSerializeCallback = void (*)(LuaUserData& self, void* data, PtrSize& size);
  27. /// @memberof LuaUserData
  28. using LuaUserDataDeserializeCallback = void (*)(const void* data, LuaUserData& self);
  29. /// @memberof LuaUserData
  30. class LuaUserDataTypeInfo
  31. {
  32. public:
  33. I64 m_signature;
  34. const char* m_typeName;
  35. PtrSize m_structureSize;
  36. LuaUserDataSerializeCallback m_serializeCallback;
  37. LuaUserDataDeserializeCallback m_deserializeCallback;
  38. };
  39. /// LUA userdata.
  40. class LuaUserData
  41. {
  42. public:
  43. /// @note NEVER ADD A DESTRUCTOR. LUA cannot call that.
  44. ~LuaUserData() = delete;
  45. I64 getSig() const
  46. {
  47. return m_sig;
  48. }
  49. void initGarbageCollected(const LuaUserDataTypeInfo* info)
  50. {
  51. ANKI_ASSERT(info);
  52. m_sig = info->m_signature;
  53. m_info = info;
  54. m_addressOrGarbageCollect = GC_MASK;
  55. }
  56. /// @note Accepting const void* is wrong because getData returns a mutable pointer. Fix that.
  57. void initPointed(const LuaUserDataTypeInfo* info, const void* ptrToObject)
  58. {
  59. ANKI_ASSERT(info);
  60. m_sig = info->m_signature;
  61. m_info = info;
  62. const U64 addr = ptrToNumber(ptrToObject);
  63. ANKI_ASSERT((addr & GC_MASK) == 0 && "Address too high, cannot encode a flag");
  64. m_addressOrGarbageCollect = addr;
  65. }
  66. Bool isGarbageCollected() const
  67. {
  68. ANKI_ASSERT(m_addressOrGarbageCollect != 0);
  69. return m_addressOrGarbageCollect == GC_MASK;
  70. }
  71. template<typename T>
  72. T* getData()
  73. {
  74. ANKI_ASSERT(m_addressOrGarbageCollect != 0);
  75. ANKI_ASSERT(getDataTypeInfoFor<T>().m_signature == m_sig);
  76. T* out = nullptr;
  77. if(isGarbageCollected())
  78. {
  79. // Garbage collected, the data -in memory- are after this object
  80. PtrSize mem = ptrToNumber(this);
  81. mem += getAlignedRoundUp(alignof(T), sizeof(LuaUserData));
  82. out = numberToPtr<T*>(mem);
  83. }
  84. else
  85. {
  86. // Pointed
  87. PtrSize mem = static_cast<PtrSize>(m_addressOrGarbageCollect);
  88. out = numberToPtr<T*>(mem);
  89. }
  90. ANKI_ASSERT(out);
  91. ANKI_ASSERT(isAligned(alignof(T), out));
  92. return out;
  93. }
  94. template<typename T>
  95. static PtrSize computeSizeForGarbageCollected()
  96. {
  97. return getAlignedRoundUp(alignof(T), sizeof(LuaUserData)) + sizeof(T);
  98. }
  99. const LuaUserDataTypeInfo& getDataTypeInfo() const
  100. {
  101. ANKI_ASSERT(m_info);
  102. return *m_info;
  103. }
  104. template<typename TWrapedType>
  105. static const LuaUserDataTypeInfo& getDataTypeInfoFor();
  106. private:
  107. static constexpr U64 GC_MASK = U64(1) << U64(63);
  108. I64 m_sig = 0; ///< Signature to identify the user data.
  109. U64 m_addressOrGarbageCollect = 0; ///< Encodes an address or a flag if it's for garbage collection.
  110. const LuaUserDataTypeInfo* m_info = nullptr;
  111. };
  112. /// @memberof LuaBinder
  113. class LuaBinderSerializeGlobalsCallback
  114. {
  115. public:
  116. virtual void write(const void* data, PtrSize dataSize) = 0;
  117. };
  118. /// A list of systems that the LuaBinder should be aware of.
  119. /// @memberof LuaBinder
  120. class LuaBinderOtherSystems
  121. {
  122. public:
  123. SceneGraph* m_sceneGraph;
  124. MainRenderer* m_renderer;
  125. };
  126. /// Lua binder class. A wrapper on top of LUA
  127. class LuaBinder
  128. {
  129. public:
  130. LuaBinder();
  131. LuaBinder(const LuaBinder&) = delete; // Non-copyable
  132. ~LuaBinder();
  133. LuaBinder& operator=(const LuaBinder&) = delete; // Non-copyable
  134. ANKI_USE_RESULT Error init(ScriptAllocator alloc, LuaBinderOtherSystems* otherSystems);
  135. lua_State* getLuaState()
  136. {
  137. ANKI_ASSERT(m_l);
  138. return m_l;
  139. }
  140. ScriptAllocator getAllocator() const
  141. {
  142. return m_alloc;
  143. }
  144. LuaBinderOtherSystems& getOtherSystems()
  145. {
  146. ANKI_ASSERT(m_otherSystems);
  147. return *m_otherSystems;
  148. }
  149. /// Expose a variable to the lua state
  150. template<typename T>
  151. static void exposeVariable(lua_State* state, CString name, T* y)
  152. {
  153. void* ptr = lua_newuserdata(state, sizeof(LuaUserData));
  154. LuaUserData* ud = static_cast<LuaUserData*>(ptr);
  155. ud->initPointed(&LuaUserData::getDataTypeInfoFor<T>(), y);
  156. luaL_setmetatable(state, LuaUserData::getDataTypeInfoFor<T>().m_typeName);
  157. lua_setglobal(state, name.cstr());
  158. }
  159. template<typename T>
  160. static void pushVariableToTheStack(lua_State* state, T* y)
  161. {
  162. void* ptr = lua_newuserdata(state, sizeof(LuaUserData));
  163. LuaUserData* ud = static_cast<LuaUserData*>(ptr);
  164. ud->initPointed(&LuaUserData::getDataTypeInfoFor<T>(), y);
  165. luaL_setmetatable(state, LuaUserData::getDataTypeInfoFor<T>().m_typeName);
  166. }
  167. /// Evaluate a string
  168. static Error evalString(lua_State* state, const CString& str);
  169. static void garbageCollect(lua_State* state)
  170. {
  171. lua_gc(state, LUA_GCCOLLECT, 0);
  172. }
  173. /// For debugging purposes
  174. static void stackDump(lua_State* l);
  175. /// Create a new LUA class
  176. static void createClass(lua_State* l, const LuaUserDataTypeInfo* typeInfo);
  177. /// Add new function in a class that it's already in the stack
  178. static void pushLuaCFuncMethod(lua_State* l, const char* name, lua_CFunction luafunc);
  179. /// Add a new static function in the class.
  180. static void pushLuaCFuncStaticMethod(lua_State* l, const char* className, const char* name, lua_CFunction luafunc);
  181. /// Add a new function.
  182. static void pushLuaCFunc(lua_State* l, const char* name, lua_CFunction luafunc);
  183. /// Dump global variables.
  184. static void serializeGlobals(lua_State* l, LuaBinderSerializeGlobalsCallback& callback);
  185. /// Deserialize global variables.
  186. static void deserializeGlobals(lua_State* l, const void* data, PtrSize dataSize);
  187. /// Make sure that the arguments match the argsCount number
  188. static ANKI_USE_RESULT Error checkArgsCount(lua_State* l, I argsCount);
  189. /// Get a number from the stack.
  190. template<typename TNumber>
  191. static ANKI_USE_RESULT Error checkNumber(lua_State* l, I32 stackIdx, TNumber& number)
  192. {
  193. lua_Number lnum;
  194. Error err = checkNumberInternal(l, stackIdx, lnum);
  195. if(!err)
  196. {
  197. number = TNumber(lnum);
  198. }
  199. return err;
  200. }
  201. /// Get a string from the stack.
  202. static ANKI_USE_RESULT Error checkString(lua_State* l, I32 stackIdx, const char*& out);
  203. /// Get some user data from the stack.
  204. /// The function uses the type signature to validate the type and not the
  205. /// typeName. That is supposed to be faster.
  206. static ANKI_USE_RESULT Error checkUserData(lua_State* l, I32 stackIdx, const LuaUserDataTypeInfo& typeInfo,
  207. LuaUserData*& out);
  208. /// Allocate memory.
  209. static void* luaAlloc(lua_State* l, size_t size, U32 alignment);
  210. /// Free memory.
  211. static void luaFree(lua_State* l, void* ptr);
  212. private:
  213. LuaBinderOtherSystems* m_otherSystems;
  214. ScriptAllocator m_alloc;
  215. lua_State* m_l = nullptr;
  216. HashMap<I64, const LuaUserDataTypeInfo*> m_userDataSigToDataInfo;
  217. static void* luaAllocCallback(void* userData, void* ptr, PtrSize osize, PtrSize nsize);
  218. static ANKI_USE_RESULT Error checkNumberInternal(lua_State* l, I32 stackIdx, lua_Number& number);
  219. };
  220. /// @}
  221. } // end namespace anki