LuaScript.cpp 13 KB

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