LuaScript.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. //
  2. // Copyright (c) 2008-2013 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 "EngineEvents.h"
  24. #include "File.h"
  25. #include "Log.h"
  26. #include "LuaScript.h"
  27. #include "ProcessUtils.h"
  28. #include "Profiler.h"
  29. #include "ResourceCache.h"
  30. #include "Scene.h"
  31. extern "C"
  32. {
  33. #include <lua.h>
  34. #include <lualib.h>
  35. #include <lauxlib.h>
  36. }
  37. #include "tolua++.h"
  38. #include "DebugNew.h"
  39. extern int tolua_AudioLuaAPI_open(lua_State*);
  40. extern int tolua_ContainerLuaAPI_open(lua_State*);
  41. extern int tolua_CoreLuaAPI_open(lua_State*);
  42. extern int tolua_EngineLuaAPI_open(lua_State*);
  43. extern int tolua_GraphicsLuaAPI_open(lua_State*);
  44. extern int tolua_InputLuaAPI_open(lua_State*);
  45. extern int tolua_IOLuaAPI_open(lua_State*);
  46. extern int tolua_MathLuaAPI_open(lua_State*);
  47. extern int tolua_NavigationLuaAPI_open(lua_State*);
  48. extern int tolua_NetworkLuaAPI_open(lua_State*);
  49. extern int tolua_PhysicsLuaAPI_open(lua_State*);
  50. extern int tolua_ResourceLuaAPI_open(lua_State*);
  51. extern int tolua_SceneLuaAPI_open(lua_State*);
  52. extern int tolua_UILuaAPI_open(lua_State*);
  53. extern int tolua_LuaScriptLuaAPI_open(lua_State*);
  54. namespace Urho3D
  55. {
  56. static Context* currentContext_ = 0;
  57. LuaScript::LuaScript(Context* context) :
  58. Object(context),
  59. luaState_(0)
  60. {
  61. currentContext_ = context_;
  62. luaState_ = luaL_newstate();
  63. if (!luaState_)
  64. {
  65. ErrorDialog("Lua Error", "Could not create Lua state.");
  66. return;
  67. }
  68. luaL_openlibs(luaState_);
  69. RegisterLoader();
  70. ReplacePrint();
  71. tolua_AudioLuaAPI_open(luaState_);
  72. tolua_ContainerLuaAPI_open(luaState_);
  73. tolua_CoreLuaAPI_open(luaState_);
  74. tolua_EngineLuaAPI_open(luaState_);
  75. tolua_GraphicsLuaAPI_open(luaState_);
  76. tolua_InputLuaAPI_open(luaState_);
  77. tolua_IOLuaAPI_open(luaState_);
  78. tolua_MathLuaAPI_open(luaState_);
  79. tolua_NavigationLuaAPI_open(luaState_);
  80. tolua_NetworkLuaAPI_open(luaState_);
  81. tolua_PhysicsLuaAPI_open(luaState_);
  82. tolua_ResourceLuaAPI_open(luaState_);
  83. tolua_SceneLuaAPI_open(luaState_);
  84. tolua_UILuaAPI_open(luaState_);
  85. tolua_LuaScriptLuaAPI_open(luaState_);
  86. // Subscribe to console commands
  87. SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(LuaScript, HandleConsoleCommand));
  88. }
  89. LuaScript::~LuaScript()
  90. {
  91. if (luaState_)
  92. lua_close(luaState_);
  93. }
  94. bool LuaScript::ExecuteFile(const String& fileName)
  95. {
  96. PROFILE(ExecuteFile);
  97. ResourceCache* cache = GetSubsystem<ResourceCache>();
  98. if (!cache)
  99. return false;
  100. SharedPtr<File> file = cache->GetFile(fileName);
  101. if (!file)
  102. return false;
  103. unsigned size = file->GetSize();
  104. char* buffer = new char[size];
  105. file->Read(buffer, size);
  106. int top = lua_gettop(luaState_);
  107. int error = luaL_loadbuffer(luaState_, buffer, size, fileName.CString());
  108. delete [] buffer;
  109. if (error)
  110. {
  111. const char* message = lua_tostring(luaState_, -1);
  112. ErrorDialog("Execute Lua File Failed", message);
  113. lua_settop(luaState_, top);
  114. return false;
  115. }
  116. if (lua_pcall(luaState_, 0, 0, 0))
  117. {
  118. const char* message = lua_tostring(luaState_, -1);
  119. ErrorDialog("Execute Lua File Failed", message);
  120. lua_settop(luaState_, top);
  121. return false;
  122. }
  123. return true;
  124. }
  125. bool LuaScript::ExecuteString(const String& string)
  126. {
  127. PROFILE(ExecuteString);
  128. int top = lua_gettop(luaState_);
  129. if (luaL_dostring(luaState_, string.CString()) != 0)
  130. {
  131. const char* message = lua_tostring(luaState_, -1);
  132. ErrorDialog("Execute Lua String Failed", message);
  133. lua_settop(luaState_, top);
  134. return false;
  135. }
  136. return true;
  137. }
  138. bool LuaScript::ExecuteFunction(const String& functionName)
  139. {
  140. PROFILE(ExecuteFunction);
  141. int top = lua_gettop(luaState_);
  142. if (!FindFunction(functionName))
  143. {
  144. lua_settop(luaState_, top);
  145. return false;
  146. }
  147. if (lua_pcall(luaState_, 0, 0, 0))
  148. {
  149. const char* message = lua_tostring(luaState_, -1);
  150. ErrorDialog("Execute Lua Function Failed", message);
  151. lua_settop(luaState_, top);
  152. return false;
  153. }
  154. return true;
  155. }
  156. void LuaScript::ScriptSendEvent(const String& eventName, VariantMap& eventData)
  157. {
  158. SendEvent(StringHash(eventName), eventData);
  159. }
  160. void LuaScript::ScriptSubscribeToEvent(const String& eventName, const String& functionName)
  161. {
  162. StringHash eventType(eventName);
  163. HashSet<Object*>* receivers = context_->GetEventReceivers(eventType);
  164. if (!receivers || !receivers->Contains(this))
  165. SubscribeToEvent(eventType, HANDLER(LuaScript, HandleEvent));
  166. eventTypeToFunctionNameMap_[eventType].Insert(functionName);
  167. }
  168. void LuaScript::ScriptSubscribeToEvent(Object* object, const String& eventName, const String& functionName)
  169. {
  170. StringHash eventType(eventName);
  171. HashSet<Object*>* receivers = context_->GetEventReceivers(object, eventType);
  172. if (!receivers || !receivers->Contains(this))
  173. SubscribeToEvent(object, eventType, HANDLER(LuaScript, HandleObjectEvent));
  174. objectToEventTypeToFunctionNameMap_[object][eventType].Insert(functionName);
  175. }
  176. void LuaScript::RegisterLoader()
  177. {
  178. lua_getglobal(luaState_, "package");
  179. lua_getfield(luaState_, -1, "loaders");
  180. // Replace first loader.
  181. lua_pushnumber(luaState_, 1);
  182. lua_pushcfunction(luaState_, &LuaScript::Loader);
  183. lua_settable(luaState_, -3);
  184. }
  185. int LuaScript::Loader(lua_State* L)
  186. {
  187. ResourceCache* cache = currentContext_->GetSubsystem<ResourceCache>();
  188. if (!cache)
  189. return 0;
  190. const char* name = luaL_checkstring(L, 1);
  191. SharedPtr<File> file = cache->GetFile(String(name) + ".lua");
  192. if (!file)
  193. return 0;
  194. unsigned size = file->GetSize();
  195. char* buffer = new char[size];
  196. file->Read(buffer, size);
  197. int top = lua_gettop(L);
  198. int error = luaL_loadbuffer(L, buffer, size, name);
  199. delete [] buffer;
  200. if (error)
  201. {
  202. const char* message = lua_tostring(L, -1);
  203. ErrorDialog("Execute Lua File Failed", message);
  204. lua_settop(L, top);
  205. return 0;
  206. }
  207. return 1;
  208. }
  209. void LuaScript::ReplacePrint()
  210. {
  211. static const struct luaL_reg reg[] =
  212. {
  213. {"print", &LuaScript::Print},
  214. { NULL, NULL}
  215. };
  216. lua_getglobal(luaState_, "_G");
  217. luaL_register(luaState_, NULL, reg);
  218. lua_pop(luaState_, 1);
  219. }
  220. int LuaScript::Print(lua_State *L)
  221. {
  222. String string;
  223. int n = lua_gettop(L);
  224. lua_getglobal(L, "tostring");
  225. for (int i = 1; i <= n; i++)
  226. {
  227. const char *s;
  228. lua_pushvalue(L, -1); /* function to be called */
  229. lua_pushvalue(L, i); /* value to print */
  230. lua_call(L, 1, 1);
  231. s = lua_tostring(L, -1); /* get result */
  232. if (s == NULL)
  233. return luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("print"));
  234. if (i > 1)
  235. string.Append(" "); // fputs("\t", stdout);
  236. string.Append(s); // fputs(s, stdout);
  237. lua_pop(L, 1); /* pop result */
  238. }
  239. LOGRAW(String("Lua: ") + string); // fputs("\n", stdout);
  240. return 0;
  241. }
  242. bool LuaScript::FindFunction(const String& functionName)
  243. {
  244. Vector<String> splitedNames = functionName.Split('.');
  245. String currentName = splitedNames.Front();
  246. lua_getglobal(luaState_, currentName.CString());
  247. if (splitedNames.Size() > 1)
  248. {
  249. if (!lua_istable(luaState_, -1))
  250. {
  251. ErrorDialog("Can Not Find Lua Table", String("Table Name = '") + currentName + "'.");
  252. return false;
  253. }
  254. for (unsigned i = 1; i < splitedNames.Size() - 1; ++i)
  255. {
  256. currentName = currentName + "." + splitedNames[i];
  257. lua_getfield(luaState_, -1, splitedNames[i].CString());
  258. if (!lua_istable(luaState_, -1))
  259. {
  260. ErrorDialog("Can Not Find Lua Table", String("Table Name = '") + currentName + "'.");
  261. return false;
  262. }
  263. }
  264. currentName = currentName + "." + splitedNames.Back().CString();
  265. lua_getfield(luaState_, -1, splitedNames.Back().CString());
  266. }
  267. if (!lua_isfunction(luaState_, -1))
  268. {
  269. ErrorDialog("Can Not Find Lua Function", String("Function Name = '") + currentName + "'.");
  270. return false;
  271. }
  272. return true;
  273. }
  274. void LuaScript::HandleEvent(StringHash eventType, VariantMap& eventData)
  275. {
  276. const HashSet<String>& functionNames = eventTypeToFunctionNameMap_[eventType];
  277. for (HashSet<String>::ConstIterator i = functionNames.Begin(); i != functionNames.End(); ++i)
  278. CallEventHandler(*i, eventType, eventData);
  279. }
  280. void LuaScript::HandleObjectEvent(StringHash eventType, VariantMap& eventData)
  281. {
  282. Object* object = GetEventSender();
  283. const HashSet<String>& functionNames = objectToEventTypeToFunctionNameMap_[object][eventType];
  284. for (HashSet<String>::ConstIterator i = functionNames.Begin(); i != functionNames.End(); ++i)
  285. CallEventHandler(*i, eventType, eventData);
  286. }
  287. void LuaScript::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  288. {
  289. using namespace ConsoleCommand;
  290. ExecuteString(eventData[P_COMMAND].GetString());
  291. }
  292. void LuaScript::CallEventHandler(const String& functionName, StringHash eventType, VariantMap& eventData )
  293. {
  294. int top = lua_gettop(luaState_);
  295. if (!FindFunction(functionName))
  296. {
  297. lua_settop(luaState_, top);
  298. return;
  299. }
  300. tolua_pushusertype(luaState_, (void*)&eventType, "StringHash");
  301. tolua_pushusertype(luaState_, (void*)&eventData, "VariantMap");
  302. if (lua_pcall(luaState_, 2, 0, 0) != 0)
  303. {
  304. const char* message = lua_tostring(luaState_, -1);
  305. ErrorDialog("Execute Lua Function Failed", message);
  306. lua_settop(luaState_, top);
  307. return;
  308. }
  309. }
  310. Context* GetContext()
  311. {
  312. return currentContext_;
  313. }
  314. }