LuaScript.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. //
  2. // Copyright (c) 2008-2015 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. 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, 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::ExecuteFile(const String& fileName)
  188. {
  189. PROFILE(ExecuteFile);
  190. #ifdef URHO3D_LUA_RAW_SCRIPT_LOADER
  191. if (ExecuteRawFile(fileName))
  192. return true;
  193. #endif
  194. ResourceCache* cache = GetSubsystem<ResourceCache>();
  195. LuaFile* luaFile = cache->GetResource<LuaFile>(fileName);
  196. return luaFile && luaFile->LoadAndExecute(luaState_);
  197. }
  198. bool LuaScript::ExecuteString(const String& string)
  199. {
  200. PROFILE(ExecuteString);
  201. int top = lua_gettop(luaState_);
  202. if (luaL_dostring(luaState_, string.CString()) != 0)
  203. {
  204. const char* message = lua_tostring(luaState_, -1);
  205. LOGERROR("Execute Lua string failed: " + String(message));
  206. lua_settop(luaState_, top);
  207. return false;
  208. }
  209. return true;
  210. }
  211. bool LuaScript::LoadRawFile(const String& fileName)
  212. {
  213. PROFILE(LoadRawFile);
  214. LOGINFO("Finding Lua file on file system: " + fileName);
  215. ResourceCache* cache = GetSubsystem<ResourceCache>();
  216. String filePath = cache->GetResourceFileName(fileName);
  217. if (filePath.Empty())
  218. {
  219. LOGINFO("Lua file not found: " + fileName);
  220. return false;
  221. }
  222. filePath = GetNativePath(filePath);
  223. LOGINFO("Loading Lua file from file system: " + filePath);
  224. int top = lua_gettop(luaState_);
  225. if (luaL_loadfile(luaState_, filePath.CString()))
  226. {
  227. const char* message = lua_tostring(luaState_, -1);
  228. LOGERROR("Load Lua file failed: " + String(message));
  229. lua_settop(luaState_, top);
  230. return false;
  231. }
  232. LOGINFO("Lua file loaded: " + filePath);
  233. return true;
  234. }
  235. bool LuaScript::ExecuteRawFile(const String& fileName)
  236. {
  237. PROFILE(ExecuteRawFile);
  238. int top = lua_gettop(luaState_);
  239. if (!LoadRawFile(fileName))
  240. return false;
  241. if (lua_pcall(luaState_, 0, 0, 0))
  242. {
  243. const char* message = lua_tostring(luaState_, -1);
  244. LOGERROR("Execute Lua file failed: " + String(message));
  245. lua_settop(luaState_, top);
  246. return false;
  247. }
  248. return true;
  249. }
  250. bool LuaScript::ExecuteFunction(const String& functionName)
  251. {
  252. LuaFunction* function = GetFunction(functionName);
  253. return function && function->BeginCall() && function->EndCall();
  254. }
  255. void LuaScript::SetExecuteConsoleCommands(bool enable)
  256. {
  257. if (enable == executeConsoleCommands_)
  258. return;
  259. executeConsoleCommands_ = enable;
  260. if (enable)
  261. SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(LuaScript, HandleConsoleCommand));
  262. else
  263. UnsubscribeFromEvent(E_CONSOLECOMMAND);
  264. }
  265. void LuaScript::RegisterLoader()
  266. {
  267. // Get package.loaders table
  268. lua_getglobal(luaState_, "package");
  269. lua_getfield(luaState_, -1, "loaders");
  270. // Add LuaScript::Loader to the end of the table
  271. lua_pushinteger(luaState_, lua_objlen(luaState_, -1) + 1);
  272. lua_pushcfunction(luaState_, &LuaScript::Loader);
  273. lua_settable(luaState_, -3);
  274. lua_pop(luaState_, 2);
  275. }
  276. int LuaScript::AtPanic(lua_State* L)
  277. {
  278. String errorMessage = luaL_checkstring(L, -1);
  279. LOGERROR("Lua error: Error message = '" + errorMessage + "'");
  280. lua_pop(L, 1);
  281. return 0;
  282. }
  283. int LuaScript::Loader(lua_State* L)
  284. {
  285. // Get module name
  286. String fileName(luaL_checkstring(L, 1));
  287. #ifdef URHO3D_LUA_RAW_SCRIPT_LOADER
  288. // First attempt to load lua script file from the file system
  289. // Attempt to load .luc file first, then fall back to .lua
  290. LuaScript* lua = ::GetContext(L)->GetSubsystem<LuaScript>();
  291. if (lua->LoadRawFile(fileName + ".luc") || lua->LoadRawFile(fileName + ".lua"))
  292. return 1;
  293. #endif
  294. ResourceCache* cache = ::GetContext(L)->GetSubsystem<ResourceCache>();
  295. // Attempt to get .luc file first
  296. LuaFile* lucFile = cache->GetResource<LuaFile>(fileName + ".luc", false);
  297. if (lucFile)
  298. return lucFile->LoadChunk(L) ? 1 : 0;
  299. // Then try to get .lua file. If this also fails, error is logged and
  300. // resource not found event is sent
  301. LuaFile* luaFile = cache->GetResource<LuaFile>(fileName + ".lua");
  302. if (luaFile)
  303. return luaFile->LoadChunk(L) ? 1 : 0;
  304. return 0;
  305. }
  306. void LuaScript::ReplacePrint()
  307. {
  308. static const struct luaL_reg reg[] =
  309. {
  310. {"print", &LuaScript::Print},
  311. {NULL, NULL}
  312. };
  313. lua_getglobal(luaState_, "_G");
  314. luaL_register(luaState_, NULL, reg);
  315. lua_pop(luaState_, 1);
  316. }
  317. int LuaScript::Print(lua_State* L)
  318. {
  319. String string;
  320. int n = lua_gettop(L);
  321. lua_getglobal(L, "tostring");
  322. for (int i = 1; i <= n; i++)
  323. {
  324. const char* s;
  325. // Function to be called
  326. lua_pushvalue(L, -1);
  327. // Value to print
  328. lua_pushvalue(L, i);
  329. lua_call(L, 1, 1);
  330. // Get result
  331. s = lua_tostring(L, -1);
  332. if (s == NULL)
  333. return luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("print"));
  334. if (i > 1)
  335. string.Append(" ");
  336. string.Append(s);
  337. // Pop result
  338. lua_pop(L, 1);
  339. }
  340. LOGRAW(string + "\n");
  341. return 0;
  342. }
  343. LuaFunction* LuaScript::GetFunction(int index)
  344. {
  345. if (!lua_isfunction(luaState_, index))
  346. return 0;
  347. const void* functionPointer = lua_topointer(luaState_, index);
  348. if (!functionPointer)
  349. return 0;
  350. HashMap<const void*, SharedPtr<LuaFunction> >::Iterator i = functionPointerToFunctionMap_.Find(functionPointer);
  351. if (i != functionPointerToFunctionMap_.End())
  352. return i->second_;
  353. lua_pushvalue(luaState_, index);
  354. int functionRef = luaL_ref(luaState_, LUA_REGISTRYINDEX);
  355. SharedPtr<LuaFunction> function(new LuaFunction(luaState_, functionRef, false));
  356. functionPointerToFunctionMap_[functionPointer] = function;
  357. return function;
  358. }
  359. LuaFunction* LuaScript::GetFunction(const String& functionName, bool silentIfNotFound)
  360. {
  361. if (!luaState_)
  362. return 0;
  363. HashMap<String, SharedPtr<LuaFunction> >::Iterator i = functionNameToFunctionMap_.Find(functionName);
  364. if (i != functionNameToFunctionMap_.End())
  365. return i->second_;
  366. int top = lua_gettop(luaState_);
  367. SharedPtr<LuaFunction> function;
  368. if (PushScriptFunction(functionName, silentIfNotFound))
  369. function = GetFunction(-1);
  370. lua_settop(luaState_, top);
  371. functionNameToFunctionMap_[functionName] = function;
  372. return function;
  373. }
  374. void LuaScript::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  375. {
  376. if (coroutineUpdate_ && coroutineUpdate_->BeginCall())
  377. {
  378. using namespace PostUpdate;
  379. float timeStep = eventData[P_TIMESTEP].GetFloat();
  380. coroutineUpdate_->PushFloat(timeStep);
  381. coroutineUpdate_->EndCall();
  382. }
  383. // Collect garbage
  384. {
  385. PROFILE(LuaCollectGarbage);
  386. lua_gc(luaState_, LUA_GCCOLLECT, 0);
  387. }
  388. }
  389. void LuaScript::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  390. {
  391. using namespace ConsoleCommand;
  392. if (eventData[P_ID].GetString() == GetTypeName())
  393. ExecuteString(eventData[P_COMMAND].GetString());
  394. }
  395. bool LuaScript::PushScriptFunction(const String& functionName, bool silentIfNotFound)
  396. {
  397. Vector<String> splitNames = functionName.Split('.');
  398. String currentName = splitNames.Front();
  399. lua_getglobal(luaState_, currentName.CString());
  400. if (splitNames.Size() > 1)
  401. {
  402. for (unsigned i = 0; i < splitNames.Size() - 1; ++i)
  403. {
  404. if (i)
  405. {
  406. currentName = currentName + "." + splitNames[i];
  407. lua_getfield(luaState_, -1, splitNames[i].CString());
  408. }
  409. if (!lua_istable(luaState_, -1))
  410. {
  411. if (!silentIfNotFound)
  412. LOGERROR("Could not find Lua table: Table name = '" + currentName + "'");
  413. return false;
  414. }
  415. }
  416. currentName = currentName + "." + splitNames.Back();
  417. lua_getfield(luaState_, -1, splitNames.Back().CString());
  418. }
  419. if (!lua_isfunction(luaState_, -1))
  420. {
  421. if (!silentIfNotFound)
  422. LOGERROR("Could not find Lua function: Function name = '" + currentName + "'");
  423. return false;
  424. }
  425. return true;
  426. }
  427. void RegisterLuaScriptLibrary(Context* context)
  428. {
  429. LuaFile::RegisterObject(context);
  430. LuaScriptInstance::RegisterObject(context);
  431. }
  432. }