2
0

LuaScript.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. SetContext(luaState_, context_);
  85. lua_atpanic(luaState_, &LuaScript::AtPanic);
  86. luaL_openlibs(luaState_);
  87. RegisterLoader();
  88. ReplacePrint();
  89. tolua_MathLuaAPI_open(luaState_);
  90. tolua_CoreLuaAPI_open(luaState_);
  91. tolua_IOLuaAPI_open(luaState_);
  92. tolua_ResourceLuaAPI_open(luaState_);
  93. tolua_SceneLuaAPI_open(luaState_);
  94. tolua_AudioLuaAPI_open(luaState_);
  95. tolua_EngineLuaAPI_open(luaState_);
  96. tolua_GraphicsLuaAPI_open(luaState_);
  97. tolua_InputLuaAPI_open(luaState_);
  98. #ifdef URHO3D_NAVIGATION
  99. tolua_NavigationLuaAPI_open(luaState_);
  100. #endif
  101. #ifdef URHO3D_NETWORK
  102. tolua_NetworkLuaAPI_open(luaState_);
  103. #endif
  104. #ifdef URHO3D_DATABASE
  105. tolua_DatabaseLuaAPI_open(luaState_);
  106. #endif
  107. #ifdef URHO3D_PHYSICS
  108. tolua_PhysicsLuaAPI_open(luaState_);
  109. #endif
  110. tolua_UILuaAPI_open(luaState_);
  111. #ifdef URHO3D_URHO2D
  112. tolua_Urho2DLuaAPI_open(luaState_);
  113. #endif
  114. tolua_LuaScriptLuaAPI_open(luaState_);
  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. SetContext(luaState_, 0);
  129. if (luaState)
  130. lua_close(luaState);
  131. }
  132. void LuaScript::AddEventHandler(const String& eventName, int functionIndex)
  133. {
  134. LuaFunction* function = GetFunction(functionIndex);
  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 functionIndex)
  145. {
  146. if (!sender)
  147. return;
  148. LuaFunction* function = GetFunction(functionIndex);
  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::SendEvent(const String& eventName, VariantMap& eventData)
  256. {
  257. Object::SendEvent(StringHash(eventName), eventData);
  258. }
  259. void LuaScript::SetExecuteConsoleCommands(bool enable)
  260. {
  261. if (enable == executeConsoleCommands_)
  262. return;
  263. executeConsoleCommands_ = enable;
  264. if (enable)
  265. SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(LuaScript, HandleConsoleCommand));
  266. else
  267. UnsubscribeFromEvent(E_CONSOLECOMMAND);
  268. }
  269. void LuaScript::RegisterLoader()
  270. {
  271. // Get package.loaders table
  272. lua_getglobal(luaState_, "package");
  273. lua_getfield(luaState_, -1, "loaders");
  274. // Add LuaScript::Loader to the end of the table
  275. lua_pushinteger(luaState_, lua_objlen(luaState_, -1) + 1);
  276. lua_pushcfunction(luaState_, &LuaScript::Loader);
  277. lua_settable(luaState_, -3);
  278. lua_pop(luaState_, 2);
  279. }
  280. int LuaScript::AtPanic(lua_State* L)
  281. {
  282. String errorMessage = luaL_checkstring(L, -1);
  283. LOGERROR("Lua error: Error message = '" + errorMessage + "'");
  284. lua_pop(L, 1);
  285. return 0;
  286. }
  287. int LuaScript::Loader(lua_State* L)
  288. {
  289. // Get module name
  290. String fileName(luaL_checkstring(L, 1));
  291. #ifdef URHO3D_LUA_RAW_SCRIPT_LOADER
  292. // First attempt to load lua script file from the file system.
  293. // Attempt to load .luc file first, then fall back to .lua.
  294. LuaScript* lua = ::GetContext(L)->GetSubsystem<LuaScript>();
  295. if (lua->LoadRawFile(fileName + ".luc") || lua->LoadRawFile(fileName + ".lua"))
  296. return 1;
  297. #endif
  298. ResourceCache* cache = ::GetContext(L)->GetSubsystem<ResourceCache>();
  299. // Attempt to get .luc file first.
  300. LuaFile* lucFile = cache->GetResource<LuaFile>(fileName + ".luc", false);
  301. if (lucFile)
  302. return lucFile->LoadChunk(L) ? 1 : 0;
  303. // Then try to get .lua file. If this also fails, error is logged and
  304. // resource not found event is sent
  305. LuaFile* luaFile = cache->GetResource<LuaFile>(fileName + ".lua");
  306. if (luaFile)
  307. return luaFile->LoadChunk(L) ? 1 : 0;
  308. return 0;
  309. }
  310. void LuaScript::ReplacePrint()
  311. {
  312. static const struct luaL_reg reg[] =
  313. {
  314. {"print", &LuaScript::Print},
  315. {NULL, NULL}
  316. };
  317. lua_getglobal(luaState_, "_G");
  318. luaL_register(luaState_, NULL, reg);
  319. lua_pop(luaState_, 1);
  320. }
  321. int LuaScript::Print(lua_State* L)
  322. {
  323. String string;
  324. int n = lua_gettop(L);
  325. lua_getglobal(L, "tostring");
  326. for (int i = 1; i <= n; i++)
  327. {
  328. const char* s;
  329. // Function to be called
  330. lua_pushvalue(L, -1);
  331. // Value to print
  332. lua_pushvalue(L, i);
  333. lua_call(L, 1, 1);
  334. // Get result
  335. s = lua_tostring(L, -1);
  336. if (s == NULL)
  337. return luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("print"));
  338. if (i > 1)
  339. string.Append(" ");
  340. string.Append(s);
  341. // Pop result
  342. lua_pop(L, 1);
  343. }
  344. LOGRAW(string + "\n");
  345. return 0;
  346. }
  347. LuaFunction* LuaScript::GetFunction(int functionIndex)
  348. {
  349. if (!lua_isfunction(luaState_, functionIndex))
  350. return 0;
  351. const void* functionPointer = lua_topointer(luaState_, functionIndex);
  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. lua_pushvalue(luaState_, functionIndex);
  358. int functionRef = luaL_ref(luaState_, LUA_REGISTRYINDEX);
  359. SharedPtr<LuaFunction> function(new LuaFunction(luaState_, functionRef, false));
  360. functionPointerToFunctionMap_[functionPointer] = function;
  361. return function;
  362. }
  363. LuaFunction* LuaScript::GetFunction(const String& functionName, bool silentIfNotFound)
  364. {
  365. if (!luaState_)
  366. return 0;
  367. HashMap<String, SharedPtr<LuaFunction> >::Iterator i = functionNameToFunctionMap_.Find(functionName);
  368. if (i != functionNameToFunctionMap_.End())
  369. return i->second_;
  370. int top = lua_gettop(luaState_);
  371. SharedPtr<LuaFunction> function;
  372. if (PushScriptFunction(functionName, silentIfNotFound))
  373. function = GetFunction(-1);
  374. lua_settop(luaState_, top);
  375. functionNameToFunctionMap_[functionName] = function;
  376. return function;
  377. }
  378. void LuaScript::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  379. {
  380. if (coroutineUpdate_ && coroutineUpdate_->BeginCall())
  381. {
  382. using namespace PostUpdate;
  383. float timeStep = eventData[P_TIMESTEP].GetFloat();
  384. coroutineUpdate_->PushFloat(timeStep);
  385. coroutineUpdate_->EndCall();
  386. }
  387. // Collect garbage
  388. {
  389. PROFILE(LuaCollectGarbage);
  390. lua_gc(luaState_, LUA_GCCOLLECT, 0);
  391. }
  392. }
  393. void LuaScript::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  394. {
  395. using namespace ConsoleCommand;
  396. if (eventData[P_ID].GetString() == GetTypeName())
  397. ExecuteString(eventData[P_COMMAND].GetString());
  398. }
  399. bool LuaScript::PushScriptFunction(const String& functionName, bool silentIfNotFound)
  400. {
  401. Vector<String> splitedNames = functionName.Split('.');
  402. String currentName = splitedNames.Front();
  403. lua_getglobal(luaState_, currentName.CString());
  404. if (splitedNames.Size() > 1)
  405. {
  406. if (!lua_istable(luaState_, -1))
  407. {
  408. LOGERROR("Could not find Lua table: Table name = '" + currentName + "'");
  409. return false;
  410. }
  411. for (unsigned i = 1; i < splitedNames.Size() - 1; ++i)
  412. {
  413. currentName = currentName + "." + splitedNames[i];
  414. lua_getfield(luaState_, -1, splitedNames[i].CString());
  415. if (!lua_istable(luaState_, -1))
  416. {
  417. LOGERROR("Could not find Lua table: Table name = '" + currentName + "'");
  418. return false;
  419. }
  420. }
  421. currentName = currentName + "." + splitedNames.Back().CString();
  422. lua_getfield(luaState_, -1, splitedNames.Back().CString());
  423. }
  424. if (!lua_isfunction(luaState_, -1))
  425. {
  426. if (!silentIfNotFound)
  427. LOGERROR("Could not find Lua function: Function name = '" + currentName + "'");
  428. return false;
  429. }
  430. return true;
  431. }
  432. void RegisterLuaScriptLibrary(Context* context)
  433. {
  434. LuaFile::RegisterObject(context);
  435. LuaScriptInstance::RegisterObject(context);
  436. }
  437. }