LuaScript.cpp 15 KB

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