LuaBinder.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. // Copyright (C) 2009-present, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Script/LuaBinder.h>
  6. #include <AnKi/Util/Logger.h>
  7. #include <AnKi/Util/Tracer.h>
  8. namespace anki {
  9. // Forward
  10. #define ANKI_SCRIPT_CALL_WRAP(x_) void wrapModule##x_(lua_State*)
  11. ANKI_SCRIPT_CALL_WRAP(Logger);
  12. ANKI_SCRIPT_CALL_WRAP(Math);
  13. ANKI_SCRIPT_CALL_WRAP(Renderer);
  14. ANKI_SCRIPT_CALL_WRAP(Scene);
  15. ANKI_SCRIPT_CALL_WRAP(Globals);
  16. #undef ANKI_SCRIPT_CALL_WRAP
  17. static void wrapModules(lua_State* l)
  18. {
  19. #define ANKI_SCRIPT_CALL_WRAP(x_) wrapModule##x_(l)
  20. ANKI_SCRIPT_CALL_WRAP(Logger);
  21. ANKI_SCRIPT_CALL_WRAP(Math);
  22. ANKI_SCRIPT_CALL_WRAP(Renderer);
  23. ANKI_SCRIPT_CALL_WRAP(Scene);
  24. ANKI_SCRIPT_CALL_WRAP(Globals);
  25. #undef ANKI_SCRIPT_CALL_WRAP
  26. }
  27. static int luaPanic(lua_State* l)
  28. {
  29. ANKI_SCRIPT_LOGF("Lua panic attack: %s", lua_tostring(l, -1));
  30. return 0;
  31. }
  32. LuaBinder::LuaBinder()
  33. {
  34. m_l = lua_newstate(luaAllocCallback, this);
  35. luaL_openlibs(m_l);
  36. lua_atpanic(m_l, &luaPanic);
  37. wrapModules(m_l);
  38. }
  39. LuaBinder::~LuaBinder()
  40. {
  41. if(m_l)
  42. {
  43. lua_close(m_l);
  44. }
  45. }
  46. void* LuaBinder::luaAllocCallback([[maybe_unused]] void* userData, void* ptr, PtrSize osize, PtrSize nsize)
  47. {
  48. ANKI_ASSERT(userData);
  49. #if 1
  50. void* out = nullptr;
  51. if(nsize == 0)
  52. {
  53. if(ptr != nullptr)
  54. {
  55. ScriptMemoryPool::getSingleton().free(ptr);
  56. }
  57. }
  58. else
  59. {
  60. // Should be doing something like realloc
  61. if(ptr == nullptr)
  62. {
  63. out = ScriptMemoryPool::getSingleton().allocate(nsize, 16);
  64. }
  65. else if(nsize <= osize)
  66. {
  67. out = ptr;
  68. }
  69. else
  70. {
  71. // realloc
  72. out = ScriptMemoryPool::getSingleton().allocate(nsize, 16);
  73. memcpy(out, ptr, osize);
  74. ScriptMemoryPool::getSingleton().free(ptr);
  75. }
  76. }
  77. #else
  78. void* out = nullptr;
  79. if(nsize == 0)
  80. {
  81. free(ptr);
  82. }
  83. else
  84. {
  85. out = realloc(ptr, nsize);
  86. }
  87. #endif
  88. return out;
  89. }
  90. Error LuaBinder::evalString(lua_State* state, const CString& str)
  91. {
  92. ANKI_TRACE_SCOPED_EVENT(LuaExec);
  93. Error err = Error::kNone;
  94. int e = luaL_dostring(state, &str[0]);
  95. if(e)
  96. {
  97. ANKI_SCRIPT_LOGE("%s", lua_tostring(state, -1));
  98. lua_pop(state, 1);
  99. err = Error::kUserData;
  100. }
  101. garbageCollect(state);
  102. return err;
  103. }
  104. void LuaBinder::createClass(lua_State* l, const LuaUserDataTypeInfo* typeInfo)
  105. {
  106. ANKI_ASSERT(typeInfo);
  107. lua_newtable(l); // push new table
  108. lua_setglobal(l, typeInfo->m_typeName); // pop and make global
  109. luaL_newmetatable(l, typeInfo->m_typeName); // push
  110. lua_pushstring(l, "__index"); // push
  111. lua_pushvalue(l, -2); // pushes copy of the metatable
  112. lua_settable(l, -3); // pop*2: metatable.__index = metatable
  113. // After all these the metatable is in the top of tha stack
  114. // Now, store the typeInfo
  115. void* ud;
  116. lua_getallocf(l, &ud);
  117. ANKI_ASSERT(ud);
  118. LuaBinder& binder = *static_cast<LuaBinder*>(ud);
  119. binder.m_userDataSigToDataInfo.emplace(typeInfo->m_signature, typeInfo);
  120. }
  121. void LuaBinder::pushLuaCFuncMethod(lua_State* l, const char* name, lua_CFunction luafunc)
  122. {
  123. lua_pushstring(l, name);
  124. lua_pushcfunction(l, luafunc);
  125. lua_settable(l, -3);
  126. }
  127. void LuaBinder::pushLuaCFuncStaticMethod(lua_State* l, const char* className, const char* name, lua_CFunction luafunc)
  128. {
  129. lua_getglobal(l, className); // push
  130. lua_pushcfunction(l, luafunc); // push
  131. lua_setfield(l, -2, name); // pop global
  132. lua_pop(l, 1); // pop cfunc
  133. }
  134. void LuaBinder::pushLuaCFunc(lua_State* l, const char* name, lua_CFunction luafunc)
  135. {
  136. lua_register(l, name, luafunc);
  137. }
  138. Error LuaBinder::checkNumberInternal(lua_State* l, I32 stackIdx, lua_Number& number)
  139. {
  140. Error err = Error::kNone;
  141. lua_Number lnum;
  142. int isnum;
  143. lnum = lua_tonumberx(l, stackIdx, &isnum);
  144. if(isnum)
  145. {
  146. number = lnum;
  147. }
  148. else
  149. {
  150. err = Error::kUserData;
  151. lua_pushfstring(l, "Number expected. Got %s", luaL_typename(l, stackIdx));
  152. }
  153. return err;
  154. }
  155. Error LuaBinder::checkString(lua_State* l, I32 stackIdx, const char*& out)
  156. {
  157. Error err = Error::kNone;
  158. const char* s = lua_tolstring(l, stackIdx, nullptr);
  159. if(s != nullptr)
  160. {
  161. out = s;
  162. }
  163. else
  164. {
  165. err = Error::kUserData;
  166. lua_pushfstring(l, "String expected. Got %s", luaL_typename(l, stackIdx));
  167. }
  168. return err;
  169. }
  170. Error LuaBinder::checkUserData(lua_State* l, I32 stackIdx, const LuaUserDataTypeInfo& typeInfo, LuaUserData*& out)
  171. {
  172. Error err = Error::kNone;
  173. void* p = lua_touserdata(l, stackIdx);
  174. if(p != nullptr)
  175. {
  176. out = reinterpret_cast<LuaUserData*>(p);
  177. if(out->getSig() == typeInfo.m_signature)
  178. {
  179. // Check using a LUA method again
  180. ANKI_ASSERT(luaL_testudata(l, stackIdx, typeInfo.m_typeName) != nullptr && "ANKI type check passes but LUA's type check failed");
  181. }
  182. else
  183. {
  184. // It's not the correct user data
  185. err = Error::kUserData;
  186. }
  187. }
  188. else
  189. {
  190. // It's not user data
  191. err = Error::kUserData;
  192. }
  193. if(err)
  194. {
  195. lua_pushfstring(l, "Userdata of %s expected. Got %s", typeInfo.m_typeName, luaL_typename(l, stackIdx));
  196. }
  197. return err;
  198. }
  199. Error LuaBinder::checkArgsCount(lua_State* l, I argsCount)
  200. {
  201. const I actualArgsCount = lua_gettop(l);
  202. if(argsCount != actualArgsCount)
  203. {
  204. lua_pushfstring(l, "Expecting %d arguments, got %d", argsCount, actualArgsCount);
  205. return Error::kUserData;
  206. }
  207. return Error::kNone;
  208. }
  209. void LuaBinder::serializeGlobals(lua_State* l, LuaBinderSerializeGlobalsCallback& callback)
  210. {
  211. ANKI_ASSERT(l);
  212. lua_pushglobaltable(l);
  213. lua_pushnil(l);
  214. while(lua_next(l, -2) != 0)
  215. {
  216. // Get type of key and value
  217. I keyType = lua_type(l, -2);
  218. I valueType = lua_type(l, -1);
  219. // Only string keys
  220. if(keyType != LUA_TSTRING)
  221. {
  222. lua_pop(l, 1);
  223. continue;
  224. }
  225. CString keyString = lua_tostring(l, -2);
  226. if(keyString.isEmpty() || keyString.getLength() == 0 || keyString[0] == '_')
  227. {
  228. lua_pop(l, 1);
  229. continue;
  230. }
  231. switch(valueType)
  232. {
  233. case LUA_TNUMBER:
  234. {
  235. // Write name
  236. callback.write(keyString.cstr(), keyString.getLength() + 1);
  237. // Write type
  238. U32 type = LUA_TNUMBER;
  239. callback.write(&type, sizeof(type));
  240. // Write value
  241. F64 val = lua_tonumber(l, -1);
  242. callback.write(&val, sizeof(val));
  243. break;
  244. }
  245. case LUA_TSTRING:
  246. {
  247. // Write name
  248. callback.write(keyString.cstr(), keyString.getLength() + 1);
  249. // Write type
  250. U32 type = LUA_TSTRING;
  251. callback.write(&type, sizeof(type));
  252. // Write str len
  253. CString val = lua_tostring(l, -1);
  254. callback.write(val.cstr(), val.getLength() + 1);
  255. break;
  256. }
  257. case LUA_TUSERDATA:
  258. {
  259. LuaUserData* ud = static_cast<LuaUserData*>(lua_touserdata(l, -1));
  260. ANKI_ASSERT(ud);
  261. LuaUserDataSerializeCallback cb = ud->getDataTypeInfo().m_serializeCallback;
  262. if(cb)
  263. {
  264. Array<U8, 256> buff;
  265. PtrSize dumpSize;
  266. cb(*ud, nullptr, dumpSize);
  267. if(dumpSize <= buff.getSize())
  268. {
  269. cb(*ud, &buff[0], dumpSize);
  270. }
  271. else
  272. {
  273. ANKI_ASSERT(!"TODO");
  274. }
  275. // Write name
  276. callback.write(keyString.cstr(), keyString.getLength() + 1);
  277. // Write type
  278. U32 type = LUA_TUSERDATA;
  279. callback.write(&type, sizeof(type));
  280. // Write sig
  281. callback.write(&ud->getDataTypeInfo().m_signature, sizeof(ud->getDataTypeInfo().m_signature));
  282. // Write data
  283. PtrSize size = dumpSize;
  284. callback.write(&size, sizeof(size));
  285. callback.write(&buff[0], dumpSize);
  286. }
  287. else
  288. {
  289. ANKI_SCRIPT_LOGW("Can't serialize variable %s. No callback provided", keyString.cstr());
  290. }
  291. break;
  292. }
  293. }
  294. lua_pop(l, 1);
  295. }
  296. }
  297. void LuaBinder::deserializeGlobals(lua_State* l, const void* data, PtrSize dataSize)
  298. {
  299. ANKI_ASSERT(dataSize > 0 && data);
  300. const U8* ptr = static_cast<const U8*>(data);
  301. const U8* end = ptr + dataSize;
  302. while(ptr < end)
  303. {
  304. // Get name
  305. CString name = reinterpret_cast<const char*>(ptr);
  306. U32 len = name.getLength();
  307. ANKI_ASSERT(len > 0);
  308. ptr += len + 1;
  309. // Get type
  310. I type = *reinterpret_cast<const U32*>(ptr);
  311. ptr += sizeof(U32);
  312. switch(type)
  313. {
  314. case LUA_TNUMBER:
  315. {
  316. const F64 val = *reinterpret_cast<const F64*>(ptr);
  317. ptr += sizeof(F64);
  318. lua_pushnumber(l, val);
  319. lua_setglobal(l, name.cstr());
  320. break;
  321. }
  322. case LUA_TSTRING:
  323. {
  324. CString val = reinterpret_cast<const char*>(ptr);
  325. const U len = val.getLength();
  326. ptr += len + 1;
  327. ANKI_ASSERT(len > 0);
  328. lua_pushstring(l, val.cstr());
  329. lua_setglobal(l, name.cstr());
  330. break;
  331. }
  332. case LUA_TUSERDATA:
  333. {
  334. // Get sig
  335. const I64 sig = *reinterpret_cast<const I64*>(ptr);
  336. ptr += sizeof(sig);
  337. // Get input data size
  338. const PtrSize dataSize = *reinterpret_cast<const PtrSize*>(ptr);
  339. ptr += sizeof(dataSize);
  340. // Get the type info
  341. void* ud;
  342. lua_getallocf(l, &ud);
  343. ANKI_ASSERT(ud);
  344. LuaBinder& binder = *static_cast<LuaBinder*>(ud);
  345. auto it = binder.m_userDataSigToDataInfo.find(sig);
  346. ANKI_ASSERT(it != binder.m_userDataSigToDataInfo.getEnd());
  347. const LuaUserDataTypeInfo* typeInfo = *it;
  348. // Create user data
  349. LuaUserData* userData = static_cast<LuaUserData*>(lua_newuserdata(l, typeInfo->m_structureSize));
  350. userData->initGarbageCollected(typeInfo);
  351. ANKI_ASSERT(typeInfo->m_deserializeCallback);
  352. typeInfo->m_deserializeCallback(ptr, *userData);
  353. ptr += dataSize;
  354. luaL_setmetatable(l, typeInfo->m_typeName);
  355. lua_setglobal(l, name.cstr());
  356. break;
  357. }
  358. }
  359. }
  360. }
  361. } // end namespace anki