LuaScript.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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 "../Core/CoreEvents.h"
  23. #include "../Engine/EngineEvents.h"
  24. #include "../IO/File.h"
  25. #include "../IO/Log.h"
  26. #include "../LuaScript/LuaFile.h"
  27. #include "../LuaScript/LuaFunction.h"
  28. #include "../LuaScript/LuaScript.h"
  29. #include "../LuaScript/LuaScriptInstance.h"
  30. #include "../Core/ProcessUtils.h"
  31. #include "../Core/Profiler.h"
  32. #include "../Resource/ResourceCache.h"
  33. #include "../Scene/Scene.h"
  34. extern "C"
  35. {
  36. #include <lualib.h>
  37. }
  38. #include <toluapp/tolua++.h>
  39. #include "../LuaScript/ToluaUtils.h"
  40. #include "../DebugNew.h"
  41. extern int tolua_AudioLuaAPI_open(lua_State*);
  42. extern int tolua_CoreLuaAPI_open(lua_State*);
  43. extern int tolua_EngineLuaAPI_open(lua_State*);
  44. extern int tolua_GraphicsLuaAPI_open(lua_State*);
  45. extern int tolua_InputLuaAPI_open(lua_State*);
  46. extern int tolua_IOLuaAPI_open(lua_State*);
  47. extern int tolua_MathLuaAPI_open(lua_State*);
  48. #ifdef URHO3D_NAVIGATION
  49. extern int tolua_NavigationLuaAPI_open(lua_State*);
  50. #endif
  51. #ifdef URHO3D_NETWORK
  52. extern int tolua_NetworkLuaAPI_open(lua_State*);
  53. #endif
  54. #ifdef URHO3D_PHYSICS
  55. extern int tolua_PhysicsLuaAPI_open(lua_State*);
  56. #endif
  57. extern int tolua_ResourceLuaAPI_open(lua_State*);
  58. extern int tolua_SceneLuaAPI_open(lua_State*);
  59. extern int tolua_UILuaAPI_open(lua_State*);
  60. #ifdef URHO3D_URHO2D
  61. extern int tolua_Urho2DLuaAPI_open(lua_State*);
  62. #endif
  63. extern int tolua_LuaScriptLuaAPI_open(lua_State*);
  64. namespace Urho3D
  65. {
  66. LuaScript::LuaScript(Context* context) :
  67. Object(context),
  68. luaState_(0),
  69. executeConsoleCommands_(false)
  70. {
  71. RegisterLuaScriptLibrary(context_);
  72. luaState_ = luaL_newstate();
  73. if (!luaState_)
  74. {
  75. LOGERROR("Could not create Lua state");
  76. return;
  77. }
  78. SetContext(luaState_, context_);
  79. lua_atpanic(luaState_, &LuaScript::AtPanic);
  80. luaL_openlibs(luaState_);
  81. RegisterLoader();
  82. ReplacePrint();
  83. tolua_MathLuaAPI_open(luaState_);
  84. tolua_CoreLuaAPI_open(luaState_);
  85. tolua_IOLuaAPI_open(luaState_);
  86. tolua_ResourceLuaAPI_open(luaState_);
  87. tolua_SceneLuaAPI_open(luaState_);
  88. tolua_AudioLuaAPI_open(luaState_);
  89. tolua_EngineLuaAPI_open(luaState_);
  90. tolua_GraphicsLuaAPI_open(luaState_);
  91. tolua_InputLuaAPI_open(luaState_);
  92. #ifdef URHO3D_NAVIGATION
  93. tolua_NavigationLuaAPI_open(luaState_);
  94. #endif
  95. #ifdef URHO3D_NETWORK
  96. tolua_NetworkLuaAPI_open(luaState_);
  97. #endif
  98. #ifdef URHO3D_PHYSICS
  99. tolua_PhysicsLuaAPI_open(luaState_);
  100. #endif
  101. tolua_UILuaAPI_open(luaState_);
  102. #ifdef URHO3D_URHO2D
  103. tolua_Urho2DLuaAPI_open(luaState_);
  104. #endif
  105. tolua_LuaScriptLuaAPI_open(luaState_);
  106. eventInvoker_ = new LuaScriptEventInvoker(context_);
  107. coroutineUpdate_ = GetFunction("coroutine.update");
  108. // Subscribe to post update
  109. SubscribeToEvent(E_POSTUPDATE, HANDLER(LuaScript, HandlePostUpdate));
  110. // Subscribe to console commands
  111. SetExecuteConsoleCommands(true);
  112. }
  113. LuaScript::~LuaScript()
  114. {
  115. lua_State* luaState = luaState_;
  116. luaState_ = 0;
  117. SetContext(luaState_, 0);
  118. if (luaState)
  119. lua_close(luaState);
  120. }
  121. void LuaScript::AddEventHandler(const String& eventName, int functionIndex)
  122. {
  123. WeakPtr<LuaFunction> function = GetFunction(functionIndex);
  124. if (function)
  125. eventInvoker_->AddEventHandler(0, eventName, function);
  126. }
  127. void LuaScript::AddEventHandler(const String& eventName, const String& functionName)
  128. {
  129. WeakPtr<LuaFunction> function = GetFunction(functionName);
  130. if (function)
  131. eventInvoker_->AddEventHandler(0, eventName, function);
  132. }
  133. void LuaScript::AddEventHandler(Object* sender, const String& eventName, int functionIndex)
  134. {
  135. if (!sender)
  136. return;
  137. WeakPtr<LuaFunction> function = GetFunction(functionIndex);
  138. if (!function)
  139. eventInvoker_->AddEventHandler(sender, eventName, function);
  140. }
  141. void LuaScript::AddEventHandler(Object* sender, const String& eventName, const String& functionName)
  142. {
  143. if (!sender)
  144. return;
  145. WeakPtr<LuaFunction> function = GetFunction(functionName);
  146. if (!function)
  147. eventInvoker_->AddEventHandler(sender, eventName, function);
  148. }
  149. void LuaScript::RemoveEventHandler(const String& eventName, int functionIndex)
  150. {
  151. WeakPtr<LuaFunction> function = GetFunction(functionIndex);
  152. if (function)
  153. eventInvoker_->RemoveEventHandler(0, eventName, function);
  154. }
  155. void LuaScript::RemoveEventHandler(const String& eventName, const String& functionName)
  156. {
  157. WeakPtr<LuaFunction> function = GetFunction(functionName);
  158. if (function)
  159. eventInvoker_->RemoveEventHandler(0, eventName, function);
  160. }
  161. void LuaScript::RemoveEventHandler(const String& eventName)
  162. {
  163. eventInvoker_->RemoveEventHandler(0, eventName, WeakPtr<LuaFunction>());
  164. }
  165. void LuaScript::RemoveEventHandler(Object* sender, const String& eventName, int functionIndex)
  166. {
  167. if (!sender)
  168. return;
  169. WeakPtr<LuaFunction> function = GetFunction(functionIndex);
  170. if (!function)
  171. eventInvoker_->RemoveEventHandler(sender, eventName, function);
  172. }
  173. void LuaScript::RemoveEventHandler(Object* sender, const String& eventName, const String& functionName)
  174. {
  175. if (!sender)
  176. return;
  177. WeakPtr<LuaFunction> function = GetFunction(functionName);
  178. if (!function)
  179. eventInvoker_->RemoveEventHandler(sender, eventName, function);
  180. }
  181. void LuaScript::RemoveEventHandler(Object* sender, const String& eventName)
  182. {
  183. if (!sender)
  184. return;
  185. eventInvoker_->RemoveEventHandler(sender, eventName, WeakPtr<LuaFunction>());
  186. }
  187. void LuaScript::RemoveEventHandlers(Object* sender)
  188. {
  189. if (!sender)
  190. return;
  191. eventInvoker_->RemoveAllEventHandlers(sender);
  192. }
  193. void LuaScript::RemoveAllEventHandlers()
  194. {
  195. eventInvoker_->RemoveAllEventHandlers(0);
  196. }
  197. void LuaScript::RemoveEventHandlersExcept(const Vector<String>& exceptionNames)
  198. {
  199. eventInvoker_->RemoveEventHandlersExcept(exceptionNames);
  200. }
  201. bool LuaScript::ExecuteFile(const String& fileName)
  202. {
  203. PROFILE(ExecuteFile);
  204. ResourceCache* cache = GetSubsystem<ResourceCache>();
  205. LuaFile* luaFile = cache->GetResource<LuaFile>(fileName);
  206. return luaFile && luaFile->LoadAndExecute(luaState_);
  207. }
  208. bool LuaScript::ExecuteString(const String& string)
  209. {
  210. PROFILE(ExecuteString);
  211. int top = lua_gettop(luaState_);
  212. if (luaL_dostring(luaState_, string.CString()) != 0)
  213. {
  214. const char* message = lua_tostring(luaState_, -1);
  215. LOGERROR("Execute Lua string failed: " + String(message));
  216. lua_settop(luaState_, top);
  217. return false;
  218. }
  219. return true;
  220. }
  221. bool LuaScript::ExecuteFunction(const String& functionName)
  222. {
  223. WeakPtr<LuaFunction> function = GetFunction(functionName);
  224. return function && function->BeginCall() && function->EndCall();
  225. }
  226. void LuaScript::SendEvent(const String& eventName, VariantMap& eventData)
  227. {
  228. Object::SendEvent(StringHash(eventName), eventData);
  229. }
  230. void LuaScript::SetExecuteConsoleCommands(bool enable)
  231. {
  232. if (enable == executeConsoleCommands_)
  233. return;
  234. executeConsoleCommands_ = enable;
  235. if (enable)
  236. SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(LuaScript, HandleConsoleCommand));
  237. else
  238. UnsubscribeFromEvent(E_CONSOLECOMMAND);
  239. }
  240. void LuaScript::RegisterLoader()
  241. {
  242. // Get package.loaders table
  243. lua_getglobal(luaState_, "package");
  244. lua_getfield(luaState_, -1, "loaders");
  245. // Add LuaScript::Loader to the end of the table
  246. lua_pushinteger(luaState_, lua_objlen(luaState_, -1) + 1);
  247. lua_pushcfunction(luaState_, &LuaScript::Loader);
  248. lua_settable(luaState_, -3);
  249. lua_pop(luaState_, 2);
  250. }
  251. int LuaScript::AtPanic(lua_State* L)
  252. {
  253. String errorMessage = luaL_checkstring(L, -1);
  254. LOGERROR("Lua error: Error message = '" + errorMessage + "'");
  255. lua_pop(L, 1);
  256. return 0;
  257. }
  258. int LuaScript::Loader(lua_State* L)
  259. {
  260. ResourceCache* cache = ::GetContext(L)->GetSubsystem<ResourceCache>();
  261. // Get module name
  262. const char* name = luaL_checkstring(L, 1);
  263. // Attempt to get .luc file first.
  264. String lucFileName = String(name) + ".luc";
  265. LuaFile* lucFile = cache->GetResource<LuaFile>(lucFileName, false);
  266. if (lucFile)
  267. return lucFile->LoadChunk(L) ? 1 : 0;
  268. // Then try to get .lua file. If this also fails, error is logged and resource not found event is sent
  269. String luaFileName = String(name) + ".lua";
  270. LuaFile* luaFile = cache->GetResource<LuaFile>(luaFileName);
  271. if (luaFile)
  272. return luaFile->LoadChunk(L) ? 1 : 0;
  273. return 0;
  274. }
  275. void LuaScript::ReplacePrint()
  276. {
  277. static const struct luaL_reg reg[] =
  278. {
  279. {"print", &LuaScript::Print},
  280. { NULL, NULL}
  281. };
  282. lua_getglobal(luaState_, "_G");
  283. luaL_register(luaState_, NULL, reg);
  284. lua_pop(luaState_, 1);
  285. }
  286. int LuaScript::Print(lua_State *L)
  287. {
  288. String string;
  289. int n = lua_gettop(L);
  290. lua_getglobal(L, "tostring");
  291. for (int i = 1; i <= n; i++)
  292. {
  293. const char *s;
  294. // Function to be called
  295. lua_pushvalue(L, -1);
  296. // Value to print
  297. lua_pushvalue(L, i);
  298. lua_call(L, 1, 1);
  299. // Get result
  300. s = lua_tostring(L, -1);
  301. if (s == NULL)
  302. return luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("print"));
  303. if (i > 1)
  304. string.Append(" ");
  305. string.Append(s);
  306. // Pop result
  307. lua_pop(L, 1);
  308. }
  309. LOGRAW(string + "\n");
  310. return 0;
  311. }
  312. WeakPtr<LuaFunction> LuaScript::GetFunction(int functionIndex)
  313. {
  314. if (!lua_isfunction(luaState_, functionIndex))
  315. return WeakPtr<LuaFunction>();
  316. const void* functionPointer = lua_topointer(luaState_, functionIndex);
  317. if (!functionPointer)
  318. return WeakPtr<LuaFunction>();
  319. HashMap<const void*, SharedPtr<LuaFunction> >::Iterator i = functionPointerToFunctionMap_.Find(functionPointer);
  320. if (i != functionPointerToFunctionMap_.End())
  321. return WeakPtr<LuaFunction>(i->second_);
  322. lua_pushvalue(luaState_, functionIndex);
  323. int functionRef = luaL_ref(luaState_, LUA_REGISTRYINDEX);
  324. SharedPtr<LuaFunction> function(new LuaFunction(luaState_, functionRef, false));
  325. functionPointerToFunctionMap_[functionPointer] = function;
  326. return WeakPtr<LuaFunction>(function);
  327. }
  328. WeakPtr<LuaFunction> LuaScript::GetFunction(const String& functionName, bool silentIfNotFound)
  329. {
  330. if (!luaState_)
  331. return WeakPtr<LuaFunction>();
  332. HashMap<String, SharedPtr<LuaFunction> >::Iterator i = functionNameToFunctionMap_.Find(functionName);
  333. if (i != functionNameToFunctionMap_.End())
  334. return WeakPtr<LuaFunction>(i->second_);
  335. int top = lua_gettop(luaState_);
  336. SharedPtr<LuaFunction> function;
  337. if (PushScriptFunction(functionName, silentIfNotFound))
  338. {
  339. int ref = luaL_ref(luaState_, LUA_REGISTRYINDEX);
  340. function = new LuaFunction(luaState_, ref);
  341. }
  342. lua_settop(luaState_, top);
  343. functionNameToFunctionMap_[functionName] = function;
  344. return WeakPtr<LuaFunction>(function);
  345. }
  346. void LuaScript::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  347. {
  348. if (coroutineUpdate_ && coroutineUpdate_->BeginCall())
  349. {
  350. using namespace PostUpdate;
  351. float timeStep = eventData[P_TIMESTEP].GetFloat();
  352. coroutineUpdate_->PushFloat(timeStep);
  353. coroutineUpdate_->EndCall();
  354. }
  355. // Collect garbage
  356. lua_gc(luaState_, LUA_GCCOLLECT, 0);
  357. }
  358. void LuaScript::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  359. {
  360. using namespace ConsoleCommand;
  361. if (eventData[P_ID].GetString() == GetTypeName())
  362. ExecuteString(eventData[P_COMMAND].GetString());
  363. }
  364. bool LuaScript::PushScriptFunction(const String& functionName, bool silentIfNotFound)
  365. {
  366. Vector<String> splitedNames = functionName.Split('.');
  367. String currentName = splitedNames.Front();
  368. lua_getglobal(luaState_, currentName.CString());
  369. if (splitedNames.Size() > 1)
  370. {
  371. if (!lua_istable(luaState_, -1))
  372. {
  373. LOGERROR("Could not find Lua table: Table name = '" + currentName + "'");
  374. return false;
  375. }
  376. for (unsigned i = 1; i < splitedNames.Size() - 1; ++i)
  377. {
  378. currentName = currentName + "." + splitedNames[i];
  379. lua_getfield(luaState_, -1, splitedNames[i].CString());
  380. if (!lua_istable(luaState_, -1))
  381. {
  382. LOGERROR("Could not find Lua table: Table name = '" + currentName + "'");
  383. return false;
  384. }
  385. }
  386. currentName = currentName + "." + splitedNames.Back().CString();
  387. lua_getfield(luaState_, -1, splitedNames.Back().CString());
  388. }
  389. if (!lua_isfunction(luaState_, -1))
  390. {
  391. if (!silentIfNotFound)
  392. LOGERROR("Could not find Lua function: Function name = '" + currentName + "'");
  393. return false;
  394. }
  395. return true;
  396. }
  397. LuaScriptEventInvoker::LuaScriptEventInvoker(Context* context) : Object(context)
  398. {
  399. }
  400. LuaScriptEventInvoker::~LuaScriptEventInvoker()
  401. {
  402. }
  403. void LuaScriptEventInvoker::AddEventHandler(Object* sender, const String& eventName, WeakPtr<LuaFunction> function)
  404. {
  405. EventTypeToLuaFunctionVectorMap& eventTypeToFunctionVectorMap = GetEventTypeToLuaFunctionVectorMap(sender);
  406. StringHash eventType(eventName);
  407. EventTypeToLuaFunctionVectorMap::Iterator i = eventTypeToFunctionVectorMap.Find(eventType);
  408. if (i == eventTypeToFunctionVectorMap.End())
  409. {
  410. eventTypeToFunctionVectorMap[eventType].Push(function);
  411. if (!sender)
  412. SubscribeToEvent(eventType, HANDLER(LuaScriptEventInvoker, HandleLuaScriptEvent));
  413. else
  414. SubscribeToEvent(sender, eventType, HANDLER(LuaScriptEventInvoker, HandleLuaScriptEvent));
  415. }
  416. else
  417. {
  418. if (!i->second_.Contains(function))
  419. i->second_.Push(function);
  420. }
  421. }
  422. void LuaScriptEventInvoker::RemoveEventHandler(Object* sender, const String& eventName, WeakPtr<LuaFunction> function)
  423. {
  424. EventTypeToLuaFunctionVectorMap& eventTypeToLuaFunctionVectorMap = GetEventTypeToLuaFunctionVectorMap(sender);
  425. StringHash eventType(eventName);
  426. EventTypeToLuaFunctionVectorMap::Iterator i = eventTypeToLuaFunctionVectorMap.Find(eventType);
  427. if (i == eventTypeToLuaFunctionVectorMap.End())
  428. return;
  429. if (function)
  430. i->second_.Remove(function);
  431. else
  432. i->second_.Clear();
  433. if (i->second_.Empty())
  434. {
  435. eventTypeToLuaFunctionVectorMap.Erase(i);
  436. if (!sender)
  437. UnsubscribeFromEvent(eventType);
  438. else
  439. UnsubscribeFromEvent(sender, eventType);
  440. }
  441. }
  442. void LuaScriptEventInvoker::RemoveAllEventHandlers(Object* sender)
  443. {
  444. if (!sender)
  445. {
  446. UnsubscribeFromAllEvents();
  447. eventTypeToLuaFunctionVectorMap.Clear();
  448. senderEventTypeToLuaFunctionVectorMap.Clear();
  449. }
  450. else
  451. {
  452. UnsubscribeFromEvents(sender);
  453. senderEventTypeToLuaFunctionVectorMap.Erase(sender);
  454. }
  455. }
  456. void LuaScriptEventInvoker::RemoveEventHandlersExcept(const Vector<String>& exceptionNames)
  457. {
  458. PODVector<StringHash> exceptionTypes(exceptionNames.Size());
  459. for (unsigned i = 0; i < exceptionTypes.Size(); ++i)
  460. {
  461. StringHash eventType(exceptionNames[i]);
  462. exceptionTypes[i] = eventType;
  463. eventTypeToLuaFunctionVectorMap.Erase(eventType);
  464. }
  465. UnsubscribeFromAllEventsExcept(exceptionTypes, false);
  466. }
  467. void LuaScriptEventInvoker::HandleLuaScriptEvent(StringHash eventType, VariantMap& eventData)
  468. {
  469. Object* sender = GetEventHandler()->GetSender();
  470. EventTypeToLuaFunctionVectorMap& eventTypeToLuaFunctionVectorMap = GetEventTypeToLuaFunctionVectorMap(sender);
  471. EventTypeToLuaFunctionVectorMap::Iterator i = eventTypeToLuaFunctionVectorMap.Find(eventType);
  472. if (i == eventTypeToLuaFunctionVectorMap.End())
  473. return;
  474. LuaFunctionVector& luaFunctionVector = i->second_;
  475. for (unsigned i = 0; i < luaFunctionVector.Size(); ++i)
  476. {
  477. WeakPtr<LuaFunction>& function = luaFunctionVector[i];
  478. if (function && function->BeginCall())
  479. {
  480. function->PushUserType(eventType, "StringHash");
  481. function->PushUserType(eventData, "VariantMap");
  482. function->EndCall();
  483. }
  484. }
  485. }
  486. void RegisterLuaScriptLibrary(Context* context)
  487. {
  488. LuaFile::RegisterObject(context);
  489. LuaScriptInstance::RegisterObject(context);
  490. }
  491. }