ScriptController.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. #include "Base.h"
  2. #include "ScriptController.h"
  3. #include "lua/lua_all_bindings.h"
  4. namespace gameplay
  5. {
  6. ScriptController* ScriptController::__instance = NULL;
  7. #define GENERATE_LUA_GET_POINTER(type, checkFunc) \
  8. /* Check that the parameter is the correct type. */ \
  9. if (!lua_istable(_lua, index)) \
  10. { \
  11. if (lua_islightuserdata(_lua, index)) \
  12. return (type*)lua_touserdata(_lua, index); \
  13. lua_pushfstring(_lua, "Expected a " #type " pointer (an array represented as a Lua table), got '%s' instead.", luaL_typename(_lua, index)); \
  14. lua_error(_lua); \
  15. return NULL; \
  16. } \
  17. \
  18. /* Create a vector to store the values. */ \
  19. std::vector<type> values; \
  20. \
  21. /* Push the first key. */ \
  22. lua_pushnil(_lua); \
  23. while (lua_next(_lua, index) != 0) \
  24. { \
  25. values.push_back(checkFunc(_lua, -1)); \
  26. \
  27. /* Remove the value we just retrieved, but leave the key for the next iteration. */ \
  28. lua_pop(_lua, 1); \
  29. } \
  30. \
  31. /* Copy the values into an array. */ \
  32. if (values.size() > 0) \
  33. { \
  34. type* ptr = new type[values.size()]; \
  35. std::copy(values.begin(), values.end(), ptr); \
  36. return ptr; \
  37. } \
  38. return NULL
  39. static bool luaCheckBool(lua_State* state, int n)
  40. {
  41. if (!lua_isboolean(state, n))
  42. {
  43. const char* msg = lua_pushfstring(state, "%s expected, got %s", lua_typename(state, LUA_TBOOLEAN), luaL_typename(state, n));
  44. luaL_argerror(state, n, msg);
  45. return false;
  46. }
  47. return (lua_toboolean(state, n) != 0);
  48. }
  49. ScriptController* ScriptController::getInstance()
  50. {
  51. return __instance;
  52. }
  53. bool* ScriptController::getBoolPointer(int index)
  54. {
  55. GENERATE_LUA_GET_POINTER(bool, luaCheckBool);
  56. }
  57. short* ScriptController::getShortPointer(int index)
  58. {
  59. GENERATE_LUA_GET_POINTER(short, (short)luaL_checkint);
  60. }
  61. int* ScriptController::getIntPointer(int index)
  62. {
  63. GENERATE_LUA_GET_POINTER(int, (int)luaL_checkint);
  64. }
  65. long* ScriptController::getLongPointer(int index)
  66. {
  67. GENERATE_LUA_GET_POINTER(long, (long)luaL_checkint);
  68. }
  69. unsigned char* ScriptController::getUnsignedCharPointer(int index)
  70. {
  71. GENERATE_LUA_GET_POINTER(unsigned char, (unsigned char)luaL_checkunsigned);
  72. }
  73. unsigned short* ScriptController::getUnsignedShortPointer(int index)
  74. {
  75. GENERATE_LUA_GET_POINTER(unsigned short, (unsigned short)luaL_checkunsigned);
  76. }
  77. unsigned int* ScriptController::getUnsignedIntPointer(int index)
  78. {
  79. GENERATE_LUA_GET_POINTER(unsigned int, (unsigned int)luaL_checkunsigned);
  80. }
  81. unsigned long* ScriptController::getUnsignedLongPointer(int index)
  82. {
  83. GENERATE_LUA_GET_POINTER(unsigned long, (unsigned long)luaL_checkunsigned);
  84. }
  85. float* ScriptController::getFloatPointer(int index)
  86. {
  87. GENERATE_LUA_GET_POINTER(float, (float)luaL_checknumber);
  88. }
  89. double* ScriptController::getDoublePointer(int index)
  90. {
  91. GENERATE_LUA_GET_POINTER(double, (double)luaL_checknumber);
  92. }
  93. void* ScriptController::getObjectPointer(int index, const char* type)
  94. {
  95. void* p = lua_touserdata(_lua, index);
  96. if (p != NULL)
  97. {
  98. if (lua_getmetatable(_lua, index))
  99. {
  100. // Check if it matches the type's metatable.
  101. luaL_getmetatable(_lua, type);
  102. if (lua_rawequal(_lua, -1, -2))
  103. {
  104. lua_pop(_lua, 2);
  105. return p;
  106. }
  107. lua_pop(_lua, 1);
  108. // Check if it matches any of the derived types' metatables.
  109. const std::vector<std::string>& types = _hierarchy[type];
  110. for (unsigned int i = 0, count = types.size(); i < count; i++)
  111. {
  112. luaL_getmetatable(_lua, types[i].c_str());
  113. if (lua_rawequal(_lua, -1, -2))
  114. {
  115. lua_pop(_lua, 2);
  116. return p;
  117. }
  118. lua_pop(_lua, 1);
  119. }
  120. lua_pop(_lua, 1);
  121. }
  122. }
  123. return NULL;
  124. }
  125. void ScriptController::loadScript(const char* path)
  126. {
  127. if (luaL_dofile(_lua, path))
  128. GP_ERROR("Failed to run Lua script with error: '%s'.", lua_tostring(_lua, -1));
  129. }
  130. bool ScriptController::getBool(const char* name)
  131. {
  132. lua_getglobal(_lua, name);
  133. return luaCheckBool(_lua, -1);
  134. }
  135. char ScriptController::getChar(const char* name)
  136. {
  137. lua_getglobal(_lua, name);
  138. return (char)luaL_checkint(_lua, -1);
  139. }
  140. short ScriptController::getShort(const char* name)
  141. {
  142. lua_getglobal(_lua, name);
  143. return (short)luaL_checkint(_lua, -1);
  144. }
  145. int ScriptController::getInt(const char* name)
  146. {
  147. lua_getglobal(_lua, name);
  148. return luaL_checkint(_lua, -1);
  149. }
  150. long ScriptController::getLong(const char* name)
  151. {
  152. lua_getglobal(_lua, name);
  153. return luaL_checklong(_lua, -1);
  154. }
  155. unsigned char ScriptController::getUnsignedChar(const char* name)
  156. {
  157. lua_getglobal(_lua, name);
  158. return (unsigned char)luaL_checkunsigned(_lua, -1);
  159. }
  160. unsigned short ScriptController::getUnsignedShort(const char* name)
  161. {
  162. lua_getglobal(_lua, name);
  163. return (unsigned short)luaL_checkunsigned(_lua, -1);
  164. }
  165. unsigned int ScriptController::getUnsignedInt(const char* name)
  166. {
  167. lua_getglobal(_lua, name);
  168. return (unsigned int)luaL_checkunsigned(_lua, -1);
  169. }
  170. unsigned long ScriptController::getUnsignedLong(const char* name)
  171. {
  172. lua_getglobal(_lua, name);
  173. return (unsigned long)luaL_checkunsigned(_lua, -1);
  174. }
  175. float ScriptController::getFloat(const char* name)
  176. {
  177. lua_getglobal(_lua, name);
  178. return (float)luaL_checknumber(_lua, -1);
  179. }
  180. double ScriptController::getDouble(const char* name)
  181. {
  182. lua_getglobal(_lua, name);
  183. return (double)luaL_checknumber(_lua, -1);
  184. }
  185. const char* ScriptController::getString(const char* name)
  186. {
  187. lua_getglobal(_lua, name);
  188. return luaL_checkstring(_lua, -1);
  189. }
  190. void ScriptController::setBool(const char* name, bool v)
  191. {
  192. lua_pushboolean(_lua, v);
  193. lua_setglobal(_lua, name);
  194. }
  195. void ScriptController::setChar(const char* name, char v)
  196. {
  197. lua_pushinteger(_lua, v);
  198. lua_setglobal(_lua, name);
  199. }
  200. void ScriptController::setShort(const char* name, short v)
  201. {
  202. lua_pushinteger(_lua, v);
  203. lua_setglobal(_lua, name);
  204. }
  205. void ScriptController::setInt(const char* name, int v)
  206. {
  207. lua_pushinteger(_lua, v);
  208. lua_setglobal(_lua, name);
  209. }
  210. void ScriptController::setLong(const char* name, long v)
  211. {
  212. lua_pushinteger(_lua, v);
  213. lua_setglobal(_lua, name);
  214. }
  215. void ScriptController::setUnsignedChar(const char* name, unsigned char v)
  216. {
  217. lua_pushunsigned(_lua, v);
  218. lua_setglobal(_lua, name);
  219. }
  220. void ScriptController::setUnsignedShort(const char* name, unsigned short v)
  221. {
  222. lua_pushunsigned(_lua, v);
  223. lua_setglobal(_lua, name);
  224. }
  225. void ScriptController::setUnsignedInt(const char* name, unsigned int v)
  226. {
  227. lua_pushunsigned(_lua, v);
  228. lua_setglobal(_lua, name);
  229. }
  230. void ScriptController::setUnsignedLong(const char* name, unsigned long v)
  231. {
  232. lua_pushunsigned(_lua, v);
  233. lua_setglobal(_lua, name);
  234. }
  235. void ScriptController::setFloat(const char* name, float v)
  236. {
  237. lua_pushnumber(_lua, v);
  238. lua_setglobal(_lua, name);
  239. }
  240. void ScriptController::setDouble(const char* name, double v)
  241. {
  242. lua_pushnumber(_lua, v);
  243. lua_setglobal(_lua, name);
  244. }
  245. void ScriptController::setString(const char* name, const char* v)
  246. {
  247. lua_pushstring(_lua, v);
  248. lua_setglobal(_lua, name);
  249. }
  250. void ScriptController::registerLibrary(const char* name, const luaL_Reg* functions)
  251. {
  252. lua_newtable(_lua);
  253. // Go through the list of functions and add them to the table.
  254. const luaL_Reg* iter = functions;
  255. for (; iter && iter->name; iter++)
  256. {
  257. lua_pushcfunction(_lua, iter->func);
  258. lua_setfield(_lua, -2, iter->name);
  259. }
  260. lua_setglobal(_lua, name);
  261. }
  262. void ScriptController::registerConstantBool(std::string name, bool value, std::vector<std::string> scopePath)
  263. {
  264. // If the constant is within a scope, get the correct parent
  265. // table on the stack before setting its value.
  266. if (scopePath.size() > 0)
  267. {
  268. lua_getglobal(_lua, scopePath[0].c_str());
  269. for (unsigned int i = 1; i < scopePath.size(); i++)
  270. {
  271. lua_pushstring(_lua, scopePath[i].c_str());
  272. lua_gettable(_lua, -2);
  273. }
  274. // Add the constant to the parent table.
  275. lua_pushboolean(_lua, value);
  276. lua_setfield(_lua, -2, name.c_str());
  277. // Pop all the parent tables off the stack.
  278. int size = scopePath.size();
  279. lua_pop(_lua, size);
  280. }
  281. else
  282. {
  283. // TODO: Currently unsupported (we don't parse for this yet).
  284. // If the constant is global, add it to the global table.
  285. lua_pushboolean(_lua, value);
  286. lua_pushvalue(_lua, -1);
  287. lua_setglobal(_lua, name.c_str());
  288. }
  289. }
  290. void ScriptController::registerConstantNumber(std::string name, double value, std::vector<std::string> scopePath)
  291. {
  292. // If the constant is within a scope, get the correct parent
  293. // table on the stack before setting its value.
  294. if (scopePath.size() > 0)
  295. {
  296. lua_getglobal(_lua, scopePath[0].c_str());
  297. for (unsigned int i = 1; i < scopePath.size(); i++)
  298. {
  299. lua_pushstring(_lua, scopePath[i].c_str());
  300. lua_gettable(_lua, -2);
  301. }
  302. // Add the constant to the parent table.
  303. lua_pushnumber(_lua, value);
  304. lua_setfield(_lua, -2, name.c_str());
  305. // Pop all the parent tables off the stack.
  306. int size = scopePath.size();
  307. lua_pop(_lua, size);
  308. }
  309. else
  310. {
  311. // TODO: Currently unsupported (we don't parse for this yet).
  312. // If the constant is global, add it to the global table.
  313. lua_pushnumber(_lua, value);
  314. lua_pushvalue(_lua, -1);
  315. lua_setglobal(_lua, name.c_str());
  316. }
  317. }
  318. void ScriptController::registerConstantString(std::string name, std::string value, std::vector<std::string> scopePath)
  319. {
  320. // If the constant is within a scope, get the correct parent
  321. // table on the stack before setting its value.
  322. if (scopePath.size() > 0)
  323. {
  324. lua_getglobal(_lua, scopePath[0].c_str());
  325. for (unsigned int i = 1; i < scopePath.size(); i++)
  326. {
  327. lua_pushstring(_lua, scopePath[i].c_str());
  328. lua_gettable(_lua, -2);
  329. }
  330. // Add the constant to the parent table.
  331. lua_pushstring(_lua, value.c_str());
  332. lua_setfield(_lua, -2, name.c_str());
  333. // Pop all the parent tables off the stack.
  334. int size = scopePath.size();
  335. lua_pop(_lua, size);
  336. }
  337. else
  338. {
  339. // TODO: Currently unsupported (we don't parse for this yet).
  340. // If the constant is global, add it to the global table.
  341. lua_pushstring(_lua, value.c_str());
  342. lua_pushvalue(_lua, -1);
  343. lua_setglobal(_lua, name.c_str());
  344. }
  345. }
  346. void ScriptController::registerClass(const char* name, const luaL_Reg* members, lua_CFunction newFunction,
  347. lua_CFunction deleteFunction, const luaL_Reg* statics, std::vector<std::string> scopePath)
  348. {
  349. // If the type is an inner type, get the correct parent
  350. // table on the stack before creating the table for the class.
  351. if (scopePath.size() > 0)
  352. {
  353. std::string tablename = name;
  354. // Strip off the scope path part of the name.
  355. lua_getglobal(_lua, scopePath[0].c_str());
  356. std::size_t index = tablename.find(scopePath[0]);
  357. if (index != tablename.npos)
  358. tablename = tablename.substr(index + scopePath[0].size());
  359. for (unsigned int i = 1; i < scopePath.size(); i++)
  360. {
  361. lua_pushstring(_lua, scopePath[i].c_str());
  362. lua_gettable(_lua, -2);
  363. index = tablename.find(scopePath[i]);
  364. if (index != tablename.npos)
  365. tablename = tablename.substr(index + scopePath[i].size());
  366. }
  367. lua_pushstring(_lua, tablename.c_str());
  368. lua_newtable(_lua);
  369. }
  370. else
  371. {
  372. // If the type is not an inner type, set it as a global table.
  373. lua_newtable(_lua);
  374. lua_pushvalue(_lua, -1);
  375. lua_setglobal(_lua, name);
  376. }
  377. // Create the metatable and populate it with the member functions.
  378. lua_pushliteral(_lua, "__metatable");
  379. luaL_newmetatable(_lua, name);
  380. if (members)
  381. luaL_setfuncs(_lua, members, 0);
  382. lua_pushstring(_lua, "__index");
  383. lua_pushvalue(_lua, -2);
  384. lua_settable(_lua, -3);
  385. // Add the delete function if it was specified.
  386. if (deleteFunction)
  387. {
  388. lua_pushstring(_lua, "__gc");
  389. lua_pushcfunction(_lua, deleteFunction);
  390. lua_settable(_lua, -3);
  391. }
  392. // Set the metatable on the main table.
  393. lua_settable(_lua, -3);
  394. // Populate the main table with the static functions.
  395. if (statics)
  396. luaL_setfuncs(_lua, statics, 0);
  397. // Set the new function(s) for the class.
  398. if (newFunction)
  399. {
  400. lua_pushliteral(_lua, "new");
  401. lua_pushcfunction(_lua, newFunction);
  402. lua_settable(_lua, -3);
  403. }
  404. // Set the table we just created within the correct parent table.
  405. if (scopePath.size() > 0)
  406. {
  407. lua_settable(_lua, -3);
  408. // Pop all the parent tables off the stack.
  409. int size = scopePath.size();
  410. lua_pop(_lua, size);
  411. }
  412. else
  413. {
  414. // Pop the main table off the stack.
  415. lua_pop(_lua, 1);
  416. }
  417. }
  418. void ScriptController::registerFunction(const char* luaFunction, lua_CFunction cppFunction)
  419. {
  420. lua_pushcfunction(_lua, cppFunction);
  421. lua_setglobal(_lua, luaFunction);
  422. }
  423. void ScriptController::setGlobalHierarchy(std::map<std::string, std::vector<std::string> > hierarchy)
  424. {
  425. _hierarchy = hierarchy;
  426. }
  427. ScriptController::ScriptController()
  428. {
  429. memset(_callbacks, 0, sizeof(std::string*) * CALLBACK_COUNT);
  430. __instance = this;
  431. }
  432. ScriptController::~ScriptController()
  433. {
  434. __instance = NULL;
  435. }
  436. void ScriptController::initialize()
  437. {
  438. _lua = luaL_newstate();
  439. if (!_lua)
  440. GP_ERROR("Failed to initialize Lua scripting engine.");
  441. luaL_openlibs(_lua);
  442. lua_RegisterAllBindings();
  443. }
  444. void ScriptController::initializeGame()
  445. {
  446. if (_callbacks[INITIALIZE])
  447. {
  448. executeFunction<void>(_callbacks[INITIALIZE]->c_str(), NULL);
  449. }
  450. }
  451. void ScriptController::finalize()
  452. {
  453. lua_close(_lua);
  454. }
  455. void ScriptController::finalizeGame()
  456. {
  457. if (_callbacks[FINALIZE])
  458. {
  459. executeFunction<void>(_callbacks[FINALIZE]->c_str(), NULL);
  460. }
  461. }
  462. void ScriptController::update(long elapsedTime)
  463. {
  464. if (_callbacks[UPDATE])
  465. {
  466. executeFunction<void>(_callbacks[UPDATE]->c_str(), "l", elapsedTime);
  467. }
  468. }
  469. void ScriptController::render(long elapsedTime)
  470. {
  471. if (_callbacks[RENDER])
  472. {
  473. executeFunction<void>(_callbacks[RENDER]->c_str(), "l", elapsedTime);
  474. }
  475. }
  476. void ScriptController::executeFunctionHelper(int resultCount, const char* func, const char* args, va_list& list)
  477. {
  478. const char* sig = args;
  479. int argumentCount = 0;
  480. lua_getglobal(_lua, func);
  481. // Push the arguments to the Lua stack if there are any.
  482. if (sig)
  483. {
  484. while (true)
  485. {
  486. if (!(*sig))
  487. break;
  488. switch(*sig++)
  489. {
  490. // Signed integers.
  491. case 'c':
  492. case 'h':
  493. case 'i':
  494. case 'l':
  495. lua_pushinteger(_lua, va_arg(list, int));
  496. break;
  497. // Unsigned integers.
  498. case 'u':
  499. // Skip past the actual type (long, int, short, char).
  500. sig++;
  501. lua_pushunsigned(_lua, va_arg(list, int));
  502. break;
  503. // Booleans.
  504. case 'b':
  505. lua_pushboolean(_lua, va_arg(list, int));
  506. break;
  507. // Floating point numbers.
  508. case 'f':
  509. case 'd':
  510. lua_pushnumber(_lua, va_arg(list, double));
  511. break;
  512. // Strings.
  513. case 's':
  514. lua_pushstring(_lua, va_arg(list, char*));
  515. break;
  516. // Pointers.
  517. case 'p':
  518. lua_pushlightuserdata(_lua, va_arg(list, void*));
  519. break;
  520. default:
  521. GP_ERROR("Invalid argument type '%d'.", *(sig - 1));
  522. }
  523. argumentCount++;
  524. luaL_checkstack(_lua, 1, "Too many arguments.");
  525. }
  526. }
  527. // Perform the function call.
  528. if (lua_pcall(_lua, argumentCount, resultCount, 0) != 0)
  529. GP_ERROR("Failed to call function '%s' with error '%s'.", func, lua_tostring(_lua, -1));
  530. }
  531. void ScriptController::registerCallback(ScriptCallback callback, std::string function)
  532. {
  533. SAFE_DELETE(_callbacks[callback]);
  534. _callbacks[callback] = new std::string(function);
  535. }
  536. }