LuaScript.cpp 15 KB

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