LuaScript.cpp 18 KB

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