LuaScript.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. //
  2. // Copyright (c) 2008-2016 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_PHYSICS
  61. extern int tolua_PhysicsLuaAPI_open(lua_State*);
  62. #endif
  63. extern int tolua_ResourceLuaAPI_open(lua_State*);
  64. extern int tolua_SceneLuaAPI_open(lua_State*);
  65. extern int tolua_UILuaAPI_open(lua_State*);
  66. #ifdef URHO3D_URHO2D
  67. extern int tolua_Urho2DLuaAPI_open(lua_State*);
  68. #endif
  69. extern int tolua_LuaScriptLuaAPI_open(lua_State*);
  70. namespace Urho3D
  71. {
  72. LuaScript::LuaScript(Context* context) :
  73. Object(context),
  74. luaState_(0),
  75. executeConsoleCommands_(false)
  76. {
  77. RegisterLuaScriptLibrary(context_);
  78. luaState_ = luaL_newstate();
  79. if (!luaState_)
  80. {
  81. URHO3D_LOGERROR("Could not create Lua state");
  82. return;
  83. }
  84. lua_atpanic(luaState_, &LuaScript::AtPanic);
  85. luaL_openlibs(luaState_);
  86. RegisterLoader();
  87. ReplacePrint();
  88. tolua_MathLuaAPI_open(luaState_);
  89. tolua_CoreLuaAPI_open(luaState_);
  90. tolua_IOLuaAPI_open(luaState_);
  91. tolua_ResourceLuaAPI_open(luaState_);
  92. tolua_SceneLuaAPI_open(luaState_);
  93. tolua_AudioLuaAPI_open(luaState_);
  94. tolua_EngineLuaAPI_open(luaState_);
  95. tolua_GraphicsLuaAPI_open(luaState_);
  96. tolua_InputLuaAPI_open(luaState_);
  97. #ifdef URHO3D_NAVIGATION
  98. tolua_NavigationLuaAPI_open(luaState_);
  99. #endif
  100. #ifdef URHO3D_NETWORK
  101. tolua_NetworkLuaAPI_open(luaState_);
  102. #endif
  103. #ifdef URHO3D_DATABASE
  104. tolua_DatabaseLuaAPI_open(luaState_);
  105. #endif
  106. #ifdef URHO3D_PHYSICS
  107. tolua_PhysicsLuaAPI_open(luaState_);
  108. #endif
  109. tolua_UILuaAPI_open(luaState_);
  110. #ifdef URHO3D_URHO2D
  111. tolua_Urho2DLuaAPI_open(luaState_);
  112. #endif
  113. tolua_LuaScriptLuaAPI_open(luaState_);
  114. SetContext(luaState_, context_);
  115. eventInvoker_ = new LuaScriptEventInvoker(context_);
  116. coroutineUpdate_ = GetFunction("coroutine.update");
  117. // Subscribe to post update
  118. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(LuaScript, HandlePostUpdate));
  119. // Subscribe to console commands
  120. SetExecuteConsoleCommands(true);
  121. }
  122. LuaScript::~LuaScript()
  123. {
  124. functionPointerToFunctionMap_.Clear();
  125. functionNameToFunctionMap_.Clear();
  126. lua_State* luaState = luaState_;
  127. luaState_ = 0;
  128. coroutineUpdate_ = 0;
  129. if (luaState)
  130. lua_close(luaState);
  131. }
  132. void LuaScript::AddEventHandler(const String& eventName, int index)
  133. {
  134. LuaFunction* function = GetFunction(index);
  135. if (function)
  136. eventInvoker_->AddEventHandler(0, eventName, function);
  137. }
  138. void LuaScript::AddEventHandler(const String& eventName, const String& functionName)
  139. {
  140. LuaFunction* function = GetFunction(functionName);
  141. if (function)
  142. eventInvoker_->AddEventHandler(0, eventName, function);
  143. }
  144. void LuaScript::AddEventHandler(Object* sender, const String& eventName, int index)
  145. {
  146. if (!sender)
  147. return;
  148. LuaFunction* function = GetFunction(index);
  149. if (function)
  150. eventInvoker_->AddEventHandler(sender, eventName, function);
  151. }
  152. void LuaScript::AddEventHandler(Object* sender, const String& eventName, const String& functionName)
  153. {
  154. if (!sender)
  155. return;
  156. LuaFunction* function = GetFunction(functionName);
  157. if (function)
  158. eventInvoker_->AddEventHandler(sender, eventName, function);
  159. }
  160. void LuaScript::RemoveEventHandler(const String& eventName)
  161. {
  162. eventInvoker_->UnsubscribeFromEvent(eventName);
  163. }
  164. void LuaScript::RemoveEventHandler(Object* sender, const String& eventName)
  165. {
  166. if (!sender)
  167. return;
  168. eventInvoker_->UnsubscribeFromEvent(sender, eventName);
  169. }
  170. void LuaScript::RemoveEventHandlers(Object* sender)
  171. {
  172. if (!sender)
  173. return;
  174. eventInvoker_->UnsubscribeFromEvents(sender);
  175. }
  176. void LuaScript::RemoveAllEventHandlers()
  177. {
  178. eventInvoker_->UnsubscribeFromAllEvents();
  179. }
  180. void LuaScript::RemoveEventHandlersExcept(const Vector<String>& exceptionNames)
  181. {
  182. PODVector<StringHash> exceptionTypes(exceptionNames.Size());
  183. for (unsigned i = 0; i < exceptionTypes.Size(); ++i)
  184. exceptionTypes[i] = StringHash(exceptionNames[i]);
  185. eventInvoker_->UnsubscribeFromAllEventsExcept(exceptionTypes, true);
  186. }
  187. bool LuaScript::HasEventHandler(const String& eventName) const
  188. {
  189. return eventInvoker_->HasSubscribedToEvent(eventName);
  190. }
  191. bool LuaScript::HasEventHandler(Object* sender, const String& eventName) const
  192. {
  193. return eventInvoker_->HasSubscribedToEvent(sender, eventName);
  194. }
  195. bool LuaScript::ExecuteFile(const String& fileName)
  196. {
  197. URHO3D_PROFILE(ExecuteFile);
  198. #ifdef URHO3D_LUA_RAW_SCRIPT_LOADER
  199. if (ExecuteRawFile(fileName))
  200. return true;
  201. #endif
  202. ResourceCache* cache = GetSubsystem<ResourceCache>();
  203. LuaFile* luaFile = cache->GetResource<LuaFile>(fileName);
  204. return luaFile && luaFile->LoadAndExecute(luaState_);
  205. }
  206. bool LuaScript::ExecuteString(const String& string)
  207. {
  208. URHO3D_PROFILE(ExecuteString);
  209. if (luaL_dostring(luaState_, string.CString()))
  210. {
  211. const char* message = lua_tostring(luaState_, -1);
  212. URHO3D_LOGERRORF("Execute Lua string failed: %s", message);
  213. lua_pop(luaState_, 1);
  214. return false;
  215. }
  216. return true;
  217. }
  218. bool LuaScript::LoadRawFile(const String& fileName)
  219. {
  220. URHO3D_PROFILE(LoadRawFile);
  221. URHO3D_LOGINFO("Finding Lua file on file system: " + fileName);
  222. ResourceCache* cache = GetSubsystem<ResourceCache>();
  223. String filePath = cache->GetResourceFileName(fileName);
  224. if (filePath.Empty())
  225. {
  226. URHO3D_LOGINFO("Lua file not found: " + fileName);
  227. return false;
  228. }
  229. filePath = GetNativePath(filePath);
  230. URHO3D_LOGINFO("Loading Lua file from file system: " + filePath);
  231. if (luaL_loadfile(luaState_, filePath.CString()))
  232. {
  233. const char* message = lua_tostring(luaState_, -1);
  234. URHO3D_LOGERRORF("Load Lua file failed: %s", message);
  235. lua_pop(luaState_, 1);
  236. return false;
  237. }
  238. URHO3D_LOGINFO("Lua file loaded: " + filePath);
  239. return true;
  240. }
  241. bool LuaScript::ExecuteRawFile(const String& fileName)
  242. {
  243. URHO3D_PROFILE(ExecuteRawFile);
  244. if (!LoadRawFile(fileName))
  245. return false;
  246. if (lua_pcall(luaState_, 0, 0, 0))
  247. {
  248. const char* message = lua_tostring(luaState_, -1);
  249. URHO3D_LOGERRORF("Execute Lua file failed: %s", message);
  250. lua_pop(luaState_, 1);
  251. return false;
  252. }
  253. return true;
  254. }
  255. bool LuaScript::ExecuteFunction(const String& functionName)
  256. {
  257. LuaFunction* function = GetFunction(functionName);
  258. return function && function->BeginCall() && function->EndCall();
  259. }
  260. void LuaScript::SetExecuteConsoleCommands(bool enable)
  261. {
  262. if (enable == executeConsoleCommands_)
  263. return;
  264. executeConsoleCommands_ = enable;
  265. if (enable)
  266. SubscribeToEvent(E_CONSOLECOMMAND, URHO3D_HANDLER(LuaScript, HandleConsoleCommand));
  267. else
  268. UnsubscribeFromEvent(E_CONSOLECOMMAND);
  269. }
  270. void LuaScript::RegisterLoader()
  271. {
  272. // Get package.loaders table
  273. lua_getglobal(luaState_, "package");
  274. lua_getfield(luaState_, -1, "loaders");
  275. // Add LuaScript::Loader to the end of the table
  276. lua_pushinteger(luaState_, lua_objlen(luaState_, -1) + 1);
  277. lua_pushcfunction(luaState_, &LuaScript::Loader);
  278. lua_settable(luaState_, -3);
  279. lua_pop(luaState_, 2);
  280. }
  281. int LuaScript::AtPanic(lua_State* L)
  282. {
  283. String errorMessage = luaL_checkstring(L, -1);
  284. URHO3D_LOGERROR("Lua error: Error message = '" + errorMessage + "'");
  285. lua_pop(L, 1);
  286. return 0;
  287. }
  288. int LuaScript::Loader(lua_State* L)
  289. {
  290. // Get module name
  291. String fileName(luaL_checkstring(L, 1));
  292. #ifdef URHO3D_LUA_RAW_SCRIPT_LOADER
  293. // First attempt to load lua script file from the file system
  294. // Attempt to load .luc file first, then fall back to .lua
  295. LuaScript* lua = ::GetContext(L)->GetSubsystem<LuaScript>();
  296. if (lua->LoadRawFile(fileName + ".luc") || lua->LoadRawFile(fileName + ".lua"))
  297. return 1;
  298. #endif
  299. ResourceCache* cache = ::GetContext(L)->GetSubsystem<ResourceCache>();
  300. // Attempt to get .luc file first
  301. LuaFile* lucFile = cache->GetResource<LuaFile>(fileName + ".luc", false);
  302. if (lucFile)
  303. return lucFile->LoadChunk(L) ? 1 : 0;
  304. // Then try to get .lua file. If this also fails, error is logged and
  305. // resource not found event is sent
  306. LuaFile* luaFile = cache->GetResource<LuaFile>(fileName + ".lua");
  307. if (luaFile)
  308. return luaFile->LoadChunk(L) ? 1 : 0;
  309. return 0;
  310. }
  311. void LuaScript::ReplacePrint()
  312. {
  313. static const struct luaL_reg reg[] =
  314. {
  315. {"print", &LuaScript::Print},
  316. {NULL, NULL}
  317. };
  318. lua_getglobal(luaState_, "_G");
  319. luaL_register(luaState_, NULL, reg);
  320. lua_pop(luaState_, 1);
  321. }
  322. int LuaScript::Print(lua_State* L)
  323. {
  324. int n = lua_gettop(L);
  325. Vector<String> strings((unsigned)n);
  326. // Call the tostring function repeatedly for each arguments in the stack
  327. lua_getglobal(L, "tostring");
  328. for (int i = 1; i <= n; ++i)
  329. {
  330. lua_pushvalue(L, -1);
  331. lua_pushvalue(L, i);
  332. lua_call(L, 1, 1);
  333. const char* s = lua_tostring(L, -1);
  334. lua_pop(L, 1);
  335. if (s)
  336. strings[i - 1] = s;
  337. else
  338. {
  339. lua_pop(L, 1);
  340. return luaL_error(L, LUA_QL("tostring") " failed at index %d to return a string to " LUA_QL("print"), i);
  341. }
  342. }
  343. lua_pop(L, 1);
  344. URHO3D_LOGRAWF("%s\n", String::Joined(strings, " ").CString());
  345. return 0;
  346. }
  347. LuaFunction* LuaScript::GetFunction(int index)
  348. {
  349. if (!lua_isfunction(luaState_, index))
  350. return 0;
  351. const void* functionPointer = lua_topointer(luaState_, index);
  352. if (!functionPointer)
  353. return 0;
  354. HashMap<const void*, SharedPtr<LuaFunction> >::Iterator i = functionPointerToFunctionMap_.Find(functionPointer);
  355. if (i != functionPointerToFunctionMap_.End())
  356. return i->second_;
  357. SharedPtr<LuaFunction> function(new LuaFunction(luaState_, index));
  358. functionPointerToFunctionMap_[functionPointer] = function;
  359. return function;
  360. }
  361. LuaFunction* LuaScript::GetFunction(const String& functionName, bool silentIfNotFound)
  362. {
  363. if (!luaState_)
  364. return 0;
  365. HashMap<String, SharedPtr<LuaFunction> >::Iterator i = functionNameToFunctionMap_.Find(functionName);
  366. if (i != functionNameToFunctionMap_.End())
  367. return i->second_;
  368. SharedPtr<LuaFunction> function;
  369. if (PushLuaFunction(luaState_, functionName))
  370. {
  371. function = GetFunction(-1);
  372. functionNameToFunctionMap_[functionName] = function;
  373. }
  374. else if (!silentIfNotFound)
  375. URHO3D_LOGERRORF("%s", lua_tostring(luaState_, -1));
  376. lua_pop(luaState_, 1);
  377. return function;
  378. }
  379. void LuaScript::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  380. {
  381. if (coroutineUpdate_ && coroutineUpdate_->BeginCall())
  382. {
  383. using namespace PostUpdate;
  384. float timeStep = eventData[P_TIMESTEP].GetFloat();
  385. coroutineUpdate_->PushFloat(timeStep);
  386. coroutineUpdate_->EndCall();
  387. }
  388. // Collect garbage
  389. {
  390. URHO3D_PROFILE(LuaCollectGarbage);
  391. lua_gc(luaState_, LUA_GCCOLLECT, 0);
  392. }
  393. }
  394. void LuaScript::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  395. {
  396. using namespace ConsoleCommand;
  397. if (eventData[P_ID].GetString() == GetTypeName())
  398. ExecuteString(eventData[P_COMMAND].GetString());
  399. }
  400. bool LuaScript::PushLuaFunction(lua_State* L, const String& functionName)
  401. {
  402. Vector<String> splitNames = functionName.Split('.');
  403. String currentName = splitNames.Front();
  404. lua_getglobal(L, currentName.CString());
  405. if (splitNames.Size() > 1)
  406. {
  407. for (unsigned i = 0; i < splitNames.Size() - 1; ++i)
  408. {
  409. if (i)
  410. {
  411. currentName = currentName + "." + splitNames[i];
  412. lua_getfield(L, -1, splitNames[i].CString());
  413. lua_replace(L, -2);
  414. }
  415. if (!lua_istable(L, -1))
  416. {
  417. lua_pop(L, 1);
  418. lua_pushstring(L, ("Could not find Lua table: Table name = '" + currentName + "'").CString());
  419. return false;
  420. }
  421. }
  422. currentName = currentName + "." + splitNames.Back();
  423. lua_getfield(L, -1, splitNames.Back().CString());
  424. lua_replace(L, -2);
  425. }
  426. if (!lua_isfunction(L, -1))
  427. {
  428. lua_pop(L, 1);
  429. lua_pushstring(L, ("Could not find Lua function: Function name = '" + currentName + "'").CString());
  430. return false;
  431. }
  432. return true;
  433. }
  434. void RegisterLuaScriptLibrary(Context* context)
  435. {
  436. LuaFile::RegisterObject(context);
  437. LuaScriptInstance::RegisterObject(context);
  438. }
  439. }