LuaScript.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/CoreEvents.h"
  24. #include "../Core/ProcessUtils.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Engine/EngineEvents.h"
  27. #include "../IO/File.h"
  28. #include "../IO/FileSystem.h"
  29. #include "../IO/Log.h"
  30. #include "../LuaScript/LuaFile.h"
  31. #include "../LuaScript/LuaFunction.h"
  32. #include "../LuaScript/LuaScript.h"
  33. #include "../LuaScript/LuaScriptEventInvoker.h"
  34. #include "../LuaScript/LuaScriptInstance.h"
  35. #include "../Resource/ResourceCache.h"
  36. #include "../Scene/Scene.h"
  37. extern "C"
  38. {
  39. #include <lualib.h>
  40. }
  41. #include <toluapp/tolua++.h>
  42. #include "../LuaScript/ToluaUtils.h"
  43. #include "../DebugNew.h"
  44. extern int tolua_AudioLuaAPI_open(lua_State*);
  45. extern int tolua_CoreLuaAPI_open(lua_State*);
  46. extern int tolua_EngineLuaAPI_open(lua_State*);
  47. extern int tolua_GraphicsLuaAPI_open(lua_State*);
  48. extern int tolua_InputLuaAPI_open(lua_State*);
  49. extern int tolua_IOLuaAPI_open(lua_State*);
  50. extern int tolua_MathLuaAPI_open(lua_State*);
  51. #ifdef URHO3D_NAVIGATION
  52. extern int tolua_NavigationLuaAPI_open(lua_State*);
  53. #endif
  54. #ifdef URHO3D_NETWORK
  55. extern int tolua_NetworkLuaAPI_open(lua_State*);
  56. #endif
  57. #ifdef URHO3D_DATABASE
  58. extern int tolua_DatabaseLuaAPI_open(lua_State*);
  59. #endif
  60. #ifdef URHO3D_IK
  61. extern int tolua_IKLuaAPI_open(lua_State*);
  62. #endif
  63. #ifdef URHO3D_PHYSICS
  64. extern int tolua_PhysicsLuaAPI_open(lua_State*);
  65. #endif
  66. extern int tolua_ResourceLuaAPI_open(lua_State*);
  67. extern int tolua_SceneLuaAPI_open(lua_State*);
  68. extern int tolua_UILuaAPI_open(lua_State*);
  69. #ifdef URHO3D_URHO2D
  70. extern int tolua_Urho2DLuaAPI_open(lua_State*);
  71. #endif
  72. extern int tolua_LuaScriptLuaAPI_open(lua_State*);
  73. namespace Urho3D
  74. {
  75. LuaScript::LuaScript(Context* context) :
  76. Object(context),
  77. luaState_(0),
  78. executeConsoleCommands_(false)
  79. {
  80. RegisterLuaScriptLibrary(context_);
  81. luaState_ = luaL_newstate();
  82. if (!luaState_)
  83. {
  84. URHO3D_LOGERROR("Could not create Lua state");
  85. return;
  86. }
  87. lua_atpanic(luaState_, &LuaScript::AtPanic);
  88. luaL_openlibs(luaState_);
  89. RegisterLoader();
  90. ReplacePrint();
  91. tolua_MathLuaAPI_open(luaState_);
  92. tolua_CoreLuaAPI_open(luaState_);
  93. tolua_IOLuaAPI_open(luaState_);
  94. tolua_ResourceLuaAPI_open(luaState_);
  95. tolua_SceneLuaAPI_open(luaState_);
  96. tolua_AudioLuaAPI_open(luaState_);
  97. tolua_EngineLuaAPI_open(luaState_);
  98. tolua_GraphicsLuaAPI_open(luaState_);
  99. tolua_InputLuaAPI_open(luaState_);
  100. #ifdef URHO3D_NAVIGATION
  101. tolua_NavigationLuaAPI_open(luaState_);
  102. #endif
  103. #ifdef URHO3D_NETWORK
  104. tolua_NetworkLuaAPI_open(luaState_);
  105. #endif
  106. #ifdef URHO3D_DATABASE
  107. tolua_DatabaseLuaAPI_open(luaState_);
  108. #endif
  109. #ifdef URHO3D_IK
  110. tolua_IKLuaAPI_open(luaState_);
  111. #endif
  112. #ifdef URHO3D_PHYSICS
  113. tolua_PhysicsLuaAPI_open(luaState_);
  114. #endif
  115. tolua_UILuaAPI_open(luaState_);
  116. #ifdef URHO3D_URHO2D
  117. tolua_Urho2DLuaAPI_open(luaState_);
  118. #endif
  119. tolua_LuaScriptLuaAPI_open(luaState_);
  120. SetContext(luaState_, context_);
  121. eventInvoker_ = new LuaScriptEventInvoker(context_);
  122. coroutineUpdate_ = GetFunction("coroutine.update");
  123. // Subscribe to post update
  124. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(LuaScript, HandlePostUpdate));
  125. // Subscribe to console commands
  126. SetExecuteConsoleCommands(true);
  127. }
  128. LuaScript::~LuaScript()
  129. {
  130. functionPointerToFunctionMap_.Clear();
  131. functionNameToFunctionMap_.Clear();
  132. lua_State* luaState = luaState_;
  133. luaState_ = 0;
  134. coroutineUpdate_ = 0;
  135. if (luaState)
  136. lua_close(luaState);
  137. }
  138. void LuaScript::AddEventHandler(const String& eventName, int index)
  139. {
  140. LuaFunction* function = GetFunction(index);
  141. if (function)
  142. eventInvoker_->AddEventHandler(0, eventName, function);
  143. }
  144. void LuaScript::AddEventHandler(const String& eventName, const String& functionName)
  145. {
  146. LuaFunction* function = GetFunction(functionName);
  147. if (function)
  148. eventInvoker_->AddEventHandler(0, eventName, function);
  149. }
  150. void LuaScript::AddEventHandler(Object* sender, const String& eventName, int index)
  151. {
  152. if (!sender)
  153. return;
  154. LuaFunction* function = GetFunction(index);
  155. if (function)
  156. eventInvoker_->AddEventHandler(sender, eventName, function);
  157. }
  158. void LuaScript::AddEventHandler(Object* sender, const String& eventName, const String& functionName)
  159. {
  160. if (!sender)
  161. return;
  162. LuaFunction* function = GetFunction(functionName);
  163. if (function)
  164. eventInvoker_->AddEventHandler(sender, eventName, function);
  165. }
  166. void LuaScript::RemoveEventHandler(const String& eventName)
  167. {
  168. eventInvoker_->UnsubscribeFromEvent(eventName);
  169. }
  170. void LuaScript::RemoveEventHandler(Object* sender, const String& eventName)
  171. {
  172. if (!sender)
  173. return;
  174. eventInvoker_->UnsubscribeFromEvent(sender, eventName);
  175. }
  176. void LuaScript::RemoveEventHandlers(Object* sender)
  177. {
  178. if (!sender)
  179. return;
  180. eventInvoker_->UnsubscribeFromEvents(sender);
  181. }
  182. void LuaScript::RemoveAllEventHandlers()
  183. {
  184. eventInvoker_->UnsubscribeFromAllEvents();
  185. }
  186. void LuaScript::RemoveEventHandlersExcept(const Vector<String>& exceptionNames)
  187. {
  188. PODVector<StringHash> exceptionTypes(exceptionNames.Size());
  189. for (unsigned i = 0; i < exceptionTypes.Size(); ++i)
  190. exceptionTypes[i] = StringHash(exceptionNames[i]);
  191. eventInvoker_->UnsubscribeFromAllEventsExcept(exceptionTypes, true);
  192. }
  193. bool LuaScript::HasEventHandler(const String& eventName) const
  194. {
  195. return eventInvoker_->HasSubscribedToEvent(eventName);
  196. }
  197. bool LuaScript::HasEventHandler(Object* sender, const String& eventName) const
  198. {
  199. return eventInvoker_->HasSubscribedToEvent(sender, eventName);
  200. }
  201. bool LuaScript::ExecuteFile(const String& fileName)
  202. {
  203. URHO3D_PROFILE(ExecuteFile);
  204. #ifdef URHO3D_LUA_RAW_SCRIPT_LOADER
  205. if (ExecuteRawFile(fileName))
  206. return true;
  207. #endif
  208. ResourceCache* cache = GetSubsystem<ResourceCache>();
  209. LuaFile* luaFile = cache->GetResource<LuaFile>(fileName);
  210. return luaFile && luaFile->LoadAndExecute(luaState_);
  211. }
  212. bool LuaScript::ExecuteString(const String& string)
  213. {
  214. URHO3D_PROFILE(ExecuteString);
  215. if (luaL_dostring(luaState_, string.CString()))
  216. {
  217. const char* message = lua_tostring(luaState_, -1);
  218. URHO3D_LOGERRORF("Execute Lua string failed: %s", message);
  219. lua_pop(luaState_, 1);
  220. return false;
  221. }
  222. return true;
  223. }
  224. bool LuaScript::LoadRawFile(const String& fileName)
  225. {
  226. URHO3D_PROFILE(LoadRawFile);
  227. URHO3D_LOGINFO("Finding Lua file on file system: " + fileName);
  228. ResourceCache* cache = GetSubsystem<ResourceCache>();
  229. String filePath = cache->GetResourceFileName(fileName);
  230. if (filePath.Empty())
  231. {
  232. URHO3D_LOGINFO("Lua file not found: " + fileName);
  233. return false;
  234. }
  235. filePath = GetNativePath(filePath);
  236. URHO3D_LOGINFO("Loading Lua file from file system: " + filePath);
  237. if (luaL_loadfile(luaState_, filePath.CString()))
  238. {
  239. const char* message = lua_tostring(luaState_, -1);
  240. URHO3D_LOGERRORF("Load Lua file failed: %s", message);
  241. lua_pop(luaState_, 1);
  242. return false;
  243. }
  244. URHO3D_LOGINFO("Lua file loaded: " + filePath);
  245. return true;
  246. }
  247. bool LuaScript::ExecuteRawFile(const String& fileName)
  248. {
  249. URHO3D_PROFILE(ExecuteRawFile);
  250. if (!LoadRawFile(fileName))
  251. return false;
  252. if (lua_pcall(luaState_, 0, 0, 0))
  253. {
  254. const char* message = lua_tostring(luaState_, -1);
  255. URHO3D_LOGERRORF("Execute Lua file failed: %s", message);
  256. lua_pop(luaState_, 1);
  257. return false;
  258. }
  259. return true;
  260. }
  261. bool LuaScript::ExecuteFunction(const String& functionName)
  262. {
  263. LuaFunction* function = GetFunction(functionName);
  264. return function && function->BeginCall() && function->EndCall();
  265. }
  266. void LuaScript::SetExecuteConsoleCommands(bool enable)
  267. {
  268. if (enable == executeConsoleCommands_)
  269. return;
  270. executeConsoleCommands_ = enable;
  271. if (enable)
  272. SubscribeToEvent(E_CONSOLECOMMAND, URHO3D_HANDLER(LuaScript, HandleConsoleCommand));
  273. else
  274. UnsubscribeFromEvent(E_CONSOLECOMMAND);
  275. }
  276. void LuaScript::RegisterLoader()
  277. {
  278. // Get package.loaders table
  279. lua_getglobal(luaState_, "package");
  280. lua_getfield(luaState_, -1, "loaders");
  281. // Add LuaScript::Loader to the end of the table
  282. lua_pushinteger(luaState_, lua_objlen(luaState_, -1) + 1);
  283. lua_pushcfunction(luaState_, &LuaScript::Loader);
  284. lua_settable(luaState_, -3);
  285. lua_pop(luaState_, 2);
  286. }
  287. int LuaScript::AtPanic(lua_State* L)
  288. {
  289. String errorMessage = luaL_checkstring(L, -1);
  290. URHO3D_LOGERROR("Lua error: Error message = '" + errorMessage + "'");
  291. lua_pop(L, 1);
  292. return 0;
  293. }
  294. int LuaScript::Loader(lua_State* L)
  295. {
  296. // Get module name
  297. String fileName(luaL_checkstring(L, 1));
  298. #ifdef URHO3D_LUA_RAW_SCRIPT_LOADER
  299. // First attempt to load lua script file from the file system
  300. // Attempt to load .luc file first, then fall back to .lua
  301. LuaScript* lua = ::GetContext(L)->GetSubsystem<LuaScript>();
  302. if (lua->LoadRawFile(fileName + ".luc") || lua->LoadRawFile(fileName + ".lua"))
  303. return 1;
  304. #endif
  305. ResourceCache* cache = ::GetContext(L)->GetSubsystem<ResourceCache>();
  306. // Attempt to get .luc file first
  307. LuaFile* lucFile = cache->GetResource<LuaFile>(fileName + ".luc", false);
  308. if (lucFile)
  309. return lucFile->LoadChunk(L) ? 1 : 0;
  310. // Then try to get .lua file. If this also fails, error is logged and
  311. // resource not found event is sent
  312. LuaFile* luaFile = cache->GetResource<LuaFile>(fileName + ".lua");
  313. if (luaFile)
  314. return luaFile->LoadChunk(L) ? 1 : 0;
  315. return 0;
  316. }
  317. void LuaScript::ReplacePrint()
  318. {
  319. static const struct luaL_reg reg[] =
  320. {
  321. {"print", &LuaScript::Print},
  322. {NULL, NULL}
  323. };
  324. lua_getglobal(luaState_, "_G");
  325. luaL_register(luaState_, NULL, reg);
  326. lua_pop(luaState_, 1);
  327. }
  328. int LuaScript::Print(lua_State* L)
  329. {
  330. int n = lua_gettop(L);
  331. Vector<String> strings((unsigned)n);
  332. // Call the tostring function repeatedly for each arguments in the stack
  333. lua_getglobal(L, "tostring");
  334. for (int i = 1; i <= n; ++i)
  335. {
  336. lua_pushvalue(L, -1);
  337. lua_pushvalue(L, i);
  338. lua_call(L, 1, 1);
  339. const char* s = lua_tostring(L, -1);
  340. lua_pop(L, 1);
  341. if (s)
  342. strings[i - 1] = s;
  343. else
  344. {
  345. lua_pop(L, 1);
  346. return luaL_error(L, LUA_QL("tostring") " failed at index %d to return a string to " LUA_QL("print"), i);
  347. }
  348. }
  349. lua_pop(L, 1);
  350. URHO3D_LOGRAWF("%s\n", String::Joined(strings, " ").CString());
  351. return 0;
  352. }
  353. LuaFunction* LuaScript::GetFunction(int index)
  354. {
  355. if (!lua_isfunction(luaState_, index))
  356. return 0;
  357. const void* functionPointer = lua_topointer(luaState_, index);
  358. if (!functionPointer)
  359. return 0;
  360. HashMap<const void*, SharedPtr<LuaFunction> >::Iterator i = functionPointerToFunctionMap_.Find(functionPointer);
  361. if (i != functionPointerToFunctionMap_.End())
  362. return i->second_;
  363. SharedPtr<LuaFunction> function(new LuaFunction(luaState_, index));
  364. functionPointerToFunctionMap_[functionPointer] = function;
  365. return function;
  366. }
  367. LuaFunction* LuaScript::GetFunction(const String& functionName, bool silentIfNotFound)
  368. {
  369. if (!luaState_)
  370. return 0;
  371. HashMap<String, SharedPtr<LuaFunction> >::Iterator i = functionNameToFunctionMap_.Find(functionName);
  372. if (i != functionNameToFunctionMap_.End())
  373. return i->second_;
  374. SharedPtr<LuaFunction> function;
  375. if (PushLuaFunction(luaState_, functionName))
  376. {
  377. function = GetFunction(-1);
  378. functionNameToFunctionMap_[functionName] = function;
  379. }
  380. else if (!silentIfNotFound)
  381. URHO3D_LOGERRORF("%s", lua_tostring(luaState_, -1));
  382. lua_pop(luaState_, 1);
  383. return function;
  384. }
  385. void LuaScript::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  386. {
  387. if (coroutineUpdate_ && coroutineUpdate_->BeginCall())
  388. {
  389. using namespace PostUpdate;
  390. float timeStep = eventData[P_TIMESTEP].GetFloat();
  391. coroutineUpdate_->PushFloat(timeStep);
  392. coroutineUpdate_->EndCall();
  393. }
  394. // Collect garbage
  395. {
  396. URHO3D_PROFILE(LuaCollectGarbage);
  397. lua_gc(luaState_, LUA_GCCOLLECT, 0);
  398. }
  399. }
  400. void LuaScript::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  401. {
  402. using namespace ConsoleCommand;
  403. if (eventData[P_ID].GetString() == GetTypeName())
  404. ExecuteString(eventData[P_COMMAND].GetString());
  405. }
  406. bool LuaScript::PushLuaFunction(lua_State* L, const String& functionName)
  407. {
  408. Vector<String> splitNames = functionName.Split('.');
  409. String currentName = splitNames.Front();
  410. lua_getglobal(L, currentName.CString());
  411. if (splitNames.Size() > 1)
  412. {
  413. for (unsigned i = 0; i < splitNames.Size() - 1; ++i)
  414. {
  415. if (i)
  416. {
  417. currentName = currentName + "." + splitNames[i];
  418. lua_getfield(L, -1, splitNames[i].CString());
  419. lua_replace(L, -2);
  420. }
  421. if (!lua_istable(L, -1))
  422. {
  423. lua_pop(L, 1);
  424. lua_pushstring(L, ("Could not find Lua table: Table name = '" + currentName + "'").CString());
  425. return false;
  426. }
  427. }
  428. currentName = currentName + "." + splitNames.Back();
  429. lua_getfield(L, -1, splitNames.Back().CString());
  430. lua_replace(L, -2);
  431. }
  432. if (!lua_isfunction(L, -1))
  433. {
  434. lua_pop(L, 1);
  435. lua_pushstring(L, ("Could not find Lua function: Function name = '" + currentName + "'").CString());
  436. return false;
  437. }
  438. return true;
  439. }
  440. void RegisterLuaScriptLibrary(Context* context)
  441. {
  442. LuaFile::RegisterObject(context);
  443. LuaScriptInstance::RegisterObject(context);
  444. }
  445. }