LuaScriptInstance.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. //
  2. // Copyright (c) 2008-2017 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 "../Core/CoreEvents.h"
  24. #include "../Core/Context.h"
  25. #include "../Core/ProcessUtils.h"
  26. #include "../IO/Log.h"
  27. #include "../IO/MemoryBuffer.h"
  28. #include "../LuaScript/LuaFile.h"
  29. #include "../LuaScript/LuaFunction.h"
  30. #include "../LuaScript/LuaScript.h"
  31. #include "../LuaScript/LuaScriptEventInvoker.h"
  32. #include "../LuaScript/LuaScriptInstance.h"
  33. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  34. #include "../Physics/PhysicsEvents.h"
  35. #endif
  36. #include "../Resource/ResourceCache.h"
  37. #include "../Scene/Scene.h"
  38. #include "../Scene/SceneEvents.h"
  39. #include <toluapp/tolua++.h>
  40. #include "../LuaScript/ToluaUtils.h"
  41. #include "../DebugNew.h"
  42. namespace Urho3D
  43. {
  44. static const char* scriptObjectMethodNames[] = {
  45. "Start",
  46. "Stop",
  47. "DelayedStart",
  48. "Update",
  49. "PostUpdate",
  50. "FixedUpdate",
  51. "FixedPostUpdate",
  52. "Load",
  53. "Save",
  54. "ReadNetworkUpdate",
  55. "WriteNetworkUpdate",
  56. "ApplyAttributes",
  57. "TransformChanged"
  58. };
  59. LuaScriptInstance::LuaScriptInstance(Context* context) :
  60. Component(context),
  61. scriptObjectRef_(LUA_REFNIL)
  62. {
  63. luaScript_ = GetSubsystem<LuaScript>();
  64. luaState_ = luaScript_->GetState();
  65. attributeInfos_ = *context_->GetAttributes(GetTypeStatic());
  66. eventInvoker_ = new LuaScriptEventInvoker(this);
  67. for (int i = 0; i < MAX_LUA_SCRIPT_OBJECT_METHODS; ++i)
  68. scriptObjectMethods_[i] = 0;
  69. }
  70. LuaScriptInstance::~LuaScriptInstance()
  71. {
  72. ReleaseObject();
  73. }
  74. void LuaScriptInstance::RegisterObject(Context* context)
  75. {
  76. context->RegisterFactory<LuaScriptInstance>(LOGIC_CATEGORY);
  77. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  78. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Script File", GetScriptFileAttr, SetScriptFileAttr, ResourceRef,
  79. ResourceRef(LuaFile::GetTypeStatic()), AM_DEFAULT);
  80. URHO3D_ACCESSOR_ATTRIBUTE("Script Object Type", GetScriptObjectType, SetScriptObjectType, String, String::EMPTY, AM_DEFAULT);
  81. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Script Data", GetScriptDataAttr, SetScriptDataAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  82. AM_FILE | AM_NOEDIT);
  83. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Script Network Data", GetScriptNetworkDataAttr, SetScriptNetworkDataAttr, PODVector<unsigned char>,
  84. Variant::emptyBuffer, AM_NET | AM_NOEDIT);
  85. }
  86. void LuaScriptInstance::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  87. {
  88. if (attr.ptr_ != (void*)0xffffffff)
  89. {
  90. Serializable::OnSetAttribute(attr, src);
  91. return;
  92. }
  93. if (scriptObjectRef_ == LUA_REFNIL)
  94. return;
  95. String name = attr.name_;
  96. unsigned length = name.Length();
  97. if (name.Back() == '_')
  98. length -= 1;
  99. int top = lua_gettop(luaState_);
  100. String functionName = String("Set") + name.Substring(0, 1).ToUpper() + name.Substring(1, length - 1);
  101. LuaFunction* function = GetScriptObjectFunction(functionName);
  102. // If set function exist
  103. if (function)
  104. {
  105. if (function->BeginCall(this))
  106. {
  107. function->PushVariant(src);
  108. function->EndCall();
  109. }
  110. }
  111. else
  112. {
  113. lua_rawgeti(luaState_, LUA_REGISTRYINDEX, scriptObjectRef_);
  114. lua_pushstring(luaState_, name.CString());
  115. switch (attr.type_)
  116. {
  117. case VAR_BOOL:
  118. lua_pushboolean(luaState_, src.GetBool());
  119. break;
  120. case VAR_DOUBLE:
  121. lua_pushnumber(luaState_, src.GetDouble());
  122. break;
  123. case VAR_STRING:
  124. tolua_pushurho3dstring(luaState_, src.GetString());
  125. break;
  126. case VAR_VECTOR2:
  127. {
  128. Vector2* value = new Vector2(src.GetVector2());
  129. tolua_pushusertype(luaState_, value, "Vector2");
  130. tolua_register_gc(luaState_, lua_gettop(luaState_));
  131. }
  132. break;
  133. case VAR_VECTOR3:
  134. {
  135. Vector3* value = new Vector3(src.GetVector3());
  136. tolua_pushusertype(luaState_, value, "Vector3");
  137. tolua_register_gc(luaState_, lua_gettop(luaState_));
  138. }
  139. break;
  140. case VAR_VECTOR4:
  141. {
  142. Vector4* value = new Vector4(src.GetVector4());
  143. tolua_pushusertype(luaState_, value, "Vector4");
  144. tolua_register_gc(luaState_, lua_gettop(luaState_));
  145. }
  146. break;
  147. case VAR_QUATERNION:
  148. {
  149. Quaternion* value = new Quaternion(src.GetQuaternion());
  150. tolua_pushusertype(luaState_, value, "Quaternion");
  151. tolua_register_gc(luaState_, lua_gettop(luaState_));
  152. }
  153. break;
  154. case VAR_COLOR:
  155. {
  156. Color* value = new Color(src.GetColor());
  157. tolua_pushusertype(luaState_, value, "Color");
  158. tolua_register_gc(luaState_, lua_gettop(luaState_));
  159. }
  160. break;
  161. case VAR_INTRECT:
  162. {
  163. IntRect* value = new IntRect(src.GetIntRect());
  164. tolua_pushusertype(luaState_, value, "IntRect");
  165. tolua_register_gc(luaState_, lua_gettop(luaState_));
  166. }
  167. break;
  168. case VAR_INTVECTOR2:
  169. {
  170. IntVector2* value = new IntVector2(src.GetIntVector2());
  171. tolua_pushusertype(luaState_, value, "IntVector2");
  172. tolua_register_gc(luaState_, lua_gettop(luaState_));
  173. }
  174. break;
  175. case VAR_INTVECTOR3:
  176. {
  177. IntVector3* value = new IntVector3(src.GetIntVector3());
  178. tolua_pushusertype(luaState_, value, "IntVector3");
  179. tolua_register_gc(luaState_, lua_gettop(luaState_));
  180. }
  181. break;
  182. default:
  183. URHO3D_LOGERROR("Unsupported data type");
  184. lua_settop(luaState_, top);
  185. return;
  186. }
  187. lua_settable(luaState_, -3);
  188. }
  189. lua_settop(luaState_, top);
  190. }
  191. void LuaScriptInstance::OnGetAttribute(const AttributeInfo& attr, Variant& dest) const
  192. {
  193. if (attr.ptr_ != (void*)0xffffffff)
  194. {
  195. Serializable::OnGetAttribute(attr, dest);
  196. return;
  197. }
  198. if (scriptObjectRef_ == LUA_REFNIL)
  199. return;
  200. String name = attr.name_;
  201. unsigned length = name.Length();
  202. if (name.Back() == '_')
  203. length -= 1;
  204. int top = lua_gettop(luaState_);
  205. String functionName = String("Get") + name.Substring(0, 1).ToUpper() + name.Substring(1, length - 1);
  206. LuaFunction* function = GetScriptObjectFunction(functionName);
  207. // If get function exist
  208. if (function)
  209. {
  210. if (function->BeginCall(this))
  211. function->EndCall(1);
  212. }
  213. else
  214. {
  215. lua_rawgeti(luaState_, LUA_REGISTRYINDEX, scriptObjectRef_);
  216. lua_pushstring(luaState_, name.CString());
  217. lua_gettable(luaState_, -2);
  218. }
  219. switch (attr.type_)
  220. {
  221. case VAR_BOOL:
  222. dest = lua_toboolean(luaState_, -1) != 0;
  223. break;
  224. case VAR_DOUBLE:
  225. dest = lua_tonumber(luaState_, -1);
  226. break;
  227. case VAR_STRING:
  228. dest = tolua_tourho3dstring(luaState_, -1, "");
  229. break;
  230. case VAR_VECTOR2:
  231. dest = *((Vector2*)tolua_tousertype(luaState_, -1, 0));
  232. break;
  233. case VAR_VECTOR3:
  234. dest = *((Vector3*)tolua_tousertype(luaState_, -1, 0));
  235. break;
  236. case VAR_VECTOR4:
  237. dest = *((Vector4*)tolua_tousertype(luaState_, -1, 0));
  238. break;
  239. case VAR_QUATERNION:
  240. dest = *((Quaternion*)tolua_tousertype(luaState_, -1, 0));
  241. break;
  242. case VAR_COLOR:
  243. dest = *((Color*)tolua_tousertype(luaState_, -1, 0));
  244. break;
  245. case VAR_INTRECT:
  246. dest = *((IntRect*)tolua_tousertype(luaState_, -1, 0));
  247. break;
  248. case VAR_INTVECTOR2:
  249. dest = *((IntVector2*)tolua_tousertype(luaState_, -1, 0));
  250. break;
  251. case VAR_INTVECTOR3:
  252. dest = *((IntVector3*)tolua_tousertype(luaState_, -1, 0));
  253. break;
  254. default:
  255. URHO3D_LOGERROR("Unsupported data type");
  256. return;
  257. }
  258. lua_settop(luaState_, top);
  259. }
  260. void LuaScriptInstance::ApplyAttributes()
  261. {
  262. LuaFunction* function = scriptObjectMethods_[LSOM_APPLYATTRIBUTES];
  263. if (function && function->BeginCall(this))
  264. function->EndCall();
  265. }
  266. void LuaScriptInstance::OnSetEnabled()
  267. {
  268. if (IsEnabledEffective())
  269. SubscribeToScriptMethodEvents();
  270. else
  271. UnsubscribeFromScriptMethodEvents();
  272. }
  273. void LuaScriptInstance::AddEventHandler(const String& eventName, int functionIndex)
  274. {
  275. LuaFunction* function = luaScript_->GetFunction(functionIndex);
  276. if (function)
  277. eventInvoker_->AddEventHandler(0, eventName, function);
  278. }
  279. void LuaScriptInstance::AddEventHandler(const String& eventName, const String& functionName)
  280. {
  281. String realFunctionName = functionName.Replaced(":", ".");
  282. LuaFunction* function = luaScript_->GetFunction(realFunctionName);
  283. if (function)
  284. eventInvoker_->AddEventHandler(0, eventName, function);
  285. }
  286. void LuaScriptInstance::AddEventHandler(Object* sender, const String& eventName, int functionIndex)
  287. {
  288. if (!sender)
  289. return;
  290. LuaFunction* function = luaScript_->GetFunction(functionIndex);
  291. if (function)
  292. eventInvoker_->AddEventHandler(sender, eventName, function);
  293. }
  294. void LuaScriptInstance::AddEventHandler(Object* sender, const String& eventName, const String& functionName)
  295. {
  296. if (!sender)
  297. return;
  298. String realFunctionName = functionName.Replaced(":", ".");
  299. LuaFunction* function = luaScript_->GetFunction(realFunctionName);
  300. if (function)
  301. eventInvoker_->AddEventHandler(sender, eventName, function);
  302. }
  303. void LuaScriptInstance::RemoveEventHandler(const String& eventName)
  304. {
  305. eventInvoker_->UnsubscribeFromEvent(eventName);
  306. }
  307. void LuaScriptInstance::RemoveEventHandler(Object* sender, const String& eventName)
  308. {
  309. if (!sender)
  310. return;
  311. eventInvoker_->UnsubscribeFromEvent(sender, eventName);
  312. }
  313. void LuaScriptInstance::RemoveEventHandlers(Object* sender)
  314. {
  315. if (!sender)
  316. return;
  317. eventInvoker_->UnsubscribeFromEvents(sender);
  318. }
  319. void LuaScriptInstance::RemoveAllEventHandlers()
  320. {
  321. eventInvoker_->UnsubscribeFromAllEvents();
  322. }
  323. void LuaScriptInstance::RemoveEventHandlersExcept(const Vector<String>& exceptionNames)
  324. {
  325. PODVector<StringHash> exceptionTypes(exceptionNames.Size());
  326. for (unsigned i = 0; i < exceptionTypes.Size(); ++i)
  327. exceptionTypes[i] = StringHash(exceptionNames[i]);
  328. eventInvoker_->UnsubscribeFromAllEventsExcept(exceptionTypes, true);
  329. }
  330. bool LuaScriptInstance::HasEventHandler(const String& eventName) const
  331. {
  332. return eventInvoker_->HasSubscribedToEvent(eventName);
  333. }
  334. bool LuaScriptInstance::HasEventHandler(Object* sender, const String& eventName) const
  335. {
  336. return eventInvoker_->HasSubscribedToEvent(sender, eventName);
  337. }
  338. bool LuaScriptInstance::CreateObject(const String& scriptObjectType)
  339. {
  340. SetScriptFile(0);
  341. SetScriptObjectType(scriptObjectType);
  342. return scriptObjectRef_ != LUA_REFNIL;
  343. }
  344. bool LuaScriptInstance::CreateObject(LuaFile* scriptFile, const String& scriptObjectType)
  345. {
  346. SetScriptFile(scriptFile);
  347. SetScriptObjectType(scriptObjectType);
  348. return scriptObjectRef_ != LUA_REFNIL;
  349. }
  350. void LuaScriptInstance::SetScriptFile(LuaFile* scriptFile)
  351. {
  352. if (scriptFile == scriptFile_)
  353. return;
  354. scriptFile_ = scriptFile;
  355. if (!scriptFile_)
  356. return;
  357. if (!scriptFile_->LoadAndExecute(luaState_))
  358. URHO3D_LOGERROR("Execute Lua file failed: " + scriptFile_->GetName());
  359. }
  360. void LuaScriptInstance::SetScriptObjectType(const String& scriptObjectType)
  361. {
  362. if (scriptObjectType == scriptObjectType_)
  363. return;
  364. ReleaseObject();
  365. LuaFunction* function = luaScript_->GetFunction("CreateScriptObjectInstance");
  366. if (!function || !function->BeginCall())
  367. return;
  368. function->PushLuaTable(scriptObjectType);
  369. function->PushUserType((void*)this, "LuaScriptInstance");
  370. // Return script object and attribute names
  371. if (!function->EndCall(2))
  372. return;
  373. GetScriptAttributes();
  374. scriptObjectType_ = scriptObjectType;
  375. scriptObjectRef_ = luaL_ref(luaState_, LUA_REGISTRYINDEX);
  376. // Find script object method refs
  377. FindScriptObjectMethodRefs();
  378. }
  379. void LuaScriptInstance::SetScriptDataAttr(const PODVector<unsigned char>& data)
  380. {
  381. if (scriptObjectRef_ == LUA_REFNIL)
  382. return;
  383. LuaFunction* function = scriptObjectMethods_[LSOM_LOAD];
  384. if (function && function->BeginCall(this))
  385. {
  386. MemoryBuffer buf(data);
  387. function->PushUserType((Deserializer&)buf, "Deserializer");
  388. function->EndCall();
  389. }
  390. }
  391. void LuaScriptInstance::SetScriptNetworkDataAttr(const PODVector<unsigned char>& data)
  392. {
  393. if (scriptObjectRef_ == LUA_REFNIL)
  394. return;
  395. LuaFunction* function = scriptObjectMethods_[LSOM_READNETWORKUPDATE];
  396. if (function && function->BeginCall(this))
  397. {
  398. MemoryBuffer buf(data);
  399. function->PushUserType((Deserializer&)buf, "Deserializer");
  400. function->EndCall();
  401. }
  402. }
  403. LuaFile* LuaScriptInstance::GetScriptFile() const
  404. {
  405. return scriptFile_;
  406. }
  407. PODVector<unsigned char> LuaScriptInstance::GetScriptDataAttr() const
  408. {
  409. if (scriptObjectRef_ == LUA_REFNIL)
  410. return PODVector<unsigned char>();
  411. VectorBuffer buf;
  412. LuaFunction* function = scriptObjectMethods_[LSOM_SAVE];
  413. if (function && function->BeginCall(this))
  414. {
  415. function->PushUserType((Serializer&)buf, "Serializer");
  416. function->EndCall();
  417. }
  418. return buf.GetBuffer();
  419. }
  420. PODVector<unsigned char> LuaScriptInstance::GetScriptNetworkDataAttr() const
  421. {
  422. if (scriptObjectRef_ == LUA_REFNIL)
  423. return PODVector<unsigned char>();
  424. VectorBuffer buf;
  425. LuaFunction* function = scriptObjectMethods_[LSOM_WRITENETWORKUPDATE];
  426. if (function && function->BeginCall(this))
  427. {
  428. function->PushUserType((Serializer&)buf, "Serializer");
  429. function->EndCall();
  430. }
  431. return buf.GetBuffer();
  432. }
  433. void LuaScriptInstance::OnSceneSet(Scene* scene)
  434. {
  435. if (scene)
  436. SubscribeToScriptMethodEvents();
  437. else
  438. UnsubscribeFromScriptMethodEvents();
  439. }
  440. void LuaScriptInstance::OnMarkedDirty(Node* node)
  441. {
  442. // Script functions are not safe from worker threads
  443. Scene* scene = GetScene();
  444. if (scene && scene->IsThreadedUpdate())
  445. {
  446. scene->DelayedMarkedDirty(this);
  447. return;
  448. }
  449. LuaFunction* function = scriptObjectMethods_[LSOM_TRANSFORMCHANGED];
  450. if (function && function->BeginCall(this))
  451. function->EndCall();
  452. }
  453. void LuaScriptInstance::GetScriptAttributes()
  454. {
  455. // Get all attribute names
  456. Vector<String> names;
  457. if (lua_istable(luaState_, -1))
  458. {
  459. size_t length = lua_objlen(luaState_, -1);
  460. for (size_t i = 1; i <= length; ++i)
  461. {
  462. lua_pushinteger(luaState_, (int)i);
  463. lua_gettable(luaState_, -2);
  464. if (!lua_isstring(luaState_, -1))
  465. {
  466. lua_pop(luaState_, 1);
  467. continue;
  468. }
  469. String name = lua_tostring(luaState_, -1);
  470. names.Push(name);
  471. lua_pop(luaState_, 1);
  472. }
  473. }
  474. lua_pop(luaState_, 1);
  475. attributeInfos_ = *context_->GetAttributes(GetTypeStatic());
  476. for (unsigned i = 0; i < names.Size(); ++i)
  477. {
  478. lua_pushstring(luaState_, names[i].CString());
  479. lua_gettable(luaState_, -2);
  480. // Get attribute type
  481. int type = lua_type(luaState_, -1);
  482. AttributeInfo info;
  483. info.mode_ = AM_FILE;
  484. info.name_ = names[i];
  485. info.ptr_ = (void*)0xffffffff;
  486. switch (type)
  487. {
  488. case LUA_TBOOLEAN:
  489. info.type_ = VAR_BOOL;
  490. break;
  491. case LUA_TNUMBER:
  492. info.type_ = VAR_DOUBLE;
  493. break;
  494. case LUA_TSTRING:
  495. info.type_ = VAR_STRING;
  496. break;
  497. case LUA_TUSERDATA:
  498. {
  499. String typeName = tolua_typename(luaState_, -1);
  500. lua_pop(luaState_, 1);
  501. if (typeName == "Vector2")
  502. info.type_ = VAR_VECTOR2;
  503. else if (typeName == "Vector3")
  504. info.type_ = VAR_VECTOR3;
  505. else if (typeName == "Vector4")
  506. info.type_ = VAR_VECTOR4;
  507. else if (typeName == "Quaternion")
  508. info.type_ = VAR_QUATERNION;
  509. else if (typeName == "Color")
  510. info.type_ = VAR_COLOR;
  511. else if (typeName == "IntRect")
  512. info.type_ = VAR_INTRECT;
  513. else if (typeName == "IntVector2")
  514. info.type_ = VAR_INTVECTOR2;
  515. else if (typeName == "IntVector3")
  516. info.type_ = VAR_INTVECTOR3;
  517. }
  518. break;
  519. default:
  520. break;
  521. }
  522. lua_pop(luaState_, 1);
  523. if (info.type_ != VAR_NONE)
  524. attributeInfos_.Push(info);
  525. }
  526. }
  527. void LuaScriptInstance::FindScriptObjectMethodRefs()
  528. {
  529. for (unsigned i = 0; i < MAX_LUA_SCRIPT_OBJECT_METHODS; ++i)
  530. scriptObjectMethods_[i] = GetScriptObjectFunction(scriptObjectMethodNames[i]);
  531. if (IsEnabledEffective())
  532. SubscribeToScriptMethodEvents();
  533. }
  534. void LuaScriptInstance::SubscribeToScriptMethodEvents()
  535. {
  536. Scene* scene = GetScene();
  537. if (scene && (scriptObjectMethods_[LSOM_UPDATE] || scriptObjectMethods_[LSOM_DELAYEDSTART]))
  538. SubscribeToEvent(scene, E_SCENEUPDATE, URHO3D_HANDLER(LuaScriptInstance, HandleUpdate));
  539. if (scene && scriptObjectMethods_[LSOM_POSTUPDATE])
  540. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, URHO3D_HANDLER(LuaScriptInstance, HandlePostUpdate));
  541. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  542. Component* world = GetFixedUpdateSource();
  543. if (world && scriptObjectMethods_[LSOM_FIXEDUPDATE])
  544. SubscribeToEvent(world, E_PHYSICSPRESTEP, URHO3D_HANDLER(LuaScriptInstance, HandleFixedUpdate));
  545. if (world && scriptObjectMethods_[LSOM_FIXEDPOSTUPDATE])
  546. SubscribeToEvent(world, E_PHYSICSPOSTSTEP, URHO3D_HANDLER(LuaScriptInstance, HandlePostFixedUpdate));
  547. #endif
  548. if (node_ && scriptObjectMethods_[LSOM_TRANSFORMCHANGED])
  549. node_->AddListener(this);
  550. }
  551. void LuaScriptInstance::UnsubscribeFromScriptMethodEvents()
  552. {
  553. UnsubscribeFromEvent(E_SCENEUPDATE);
  554. UnsubscribeFromEvent(E_SCENEPOSTUPDATE);
  555. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  556. UnsubscribeFromEvent(E_PHYSICSPRESTEP);
  557. UnsubscribeFromEvent(E_PHYSICSPOSTSTEP);
  558. #endif
  559. if (node_ && scriptObjectMethods_[LSOM_TRANSFORMCHANGED])
  560. node_->RemoveListener(this);
  561. }
  562. void LuaScriptInstance::HandleUpdate(StringHash eventType, VariantMap& eventData)
  563. {
  564. using namespace Update;
  565. float timeStep = eventData[P_TIMESTEP].GetFloat();
  566. // Execute delayed start before first update
  567. if (scriptObjectMethods_[LSOM_DELAYEDSTART])
  568. {
  569. if (scriptObjectMethods_[LSOM_DELAYEDSTART]->BeginCall(this))
  570. scriptObjectMethods_[LSOM_DELAYEDSTART]->EndCall();
  571. scriptObjectMethods_[LSOM_DELAYEDSTART] = 0; // Only execute once
  572. }
  573. LuaFunction* function = scriptObjectMethods_[LSOM_UPDATE];
  574. if (function && function->BeginCall(this))
  575. {
  576. function->PushFloat(timeStep);
  577. function->EndCall();
  578. }
  579. }
  580. void LuaScriptInstance::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  581. {
  582. using namespace PostUpdate;
  583. float timeStep = eventData[P_TIMESTEP].GetFloat();
  584. LuaFunction* function = scriptObjectMethods_[LSOM_POSTUPDATE];
  585. if (function && function->BeginCall(this))
  586. {
  587. function->PushFloat(timeStep);
  588. function->EndCall();
  589. }
  590. }
  591. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  592. void LuaScriptInstance::HandleFixedUpdate(StringHash eventType, VariantMap& eventData)
  593. {
  594. // Execute delayed start before first fixed update if not called yet
  595. if (scriptObjectMethods_[LSOM_DELAYEDSTART])
  596. {
  597. if (scriptObjectMethods_[LSOM_DELAYEDSTART]->BeginCall(this))
  598. scriptObjectMethods_[LSOM_DELAYEDSTART]->EndCall();
  599. scriptObjectMethods_[LSOM_DELAYEDSTART] = 0; // Only execute once
  600. }
  601. using namespace PhysicsPreStep;
  602. float timeStep = eventData[P_TIMESTEP].GetFloat();
  603. LuaFunction* function = scriptObjectMethods_[LSOM_FIXEDUPDATE];
  604. if (function && function->BeginCall(this))
  605. {
  606. function->PushFloat(timeStep);
  607. function->EndCall();
  608. }
  609. }
  610. void LuaScriptInstance::HandlePostFixedUpdate(StringHash eventType, VariantMap& eventData)
  611. {
  612. using namespace PhysicsPostStep;
  613. float timeStep = eventData[P_TIMESTEP].GetFloat();
  614. LuaFunction* function = scriptObjectMethods_[LSOM_FIXEDPOSTUPDATE];
  615. if (function && function->BeginCall(this))
  616. {
  617. function->PushFloat(timeStep);
  618. function->EndCall();
  619. }
  620. }
  621. #endif
  622. void LuaScriptInstance::ReleaseObject()
  623. {
  624. if (scriptObjectRef_ == LUA_REFNIL)
  625. return;
  626. attributeInfos_ = *context_->GetAttributes(GetTypeStatic());
  627. if (IsEnabledEffective())
  628. UnsubscribeFromScriptMethodEvents();
  629. // Unref script object
  630. luaL_unref(luaState_, LUA_REGISTRYINDEX, scriptObjectRef_);
  631. scriptObjectRef_ = LUA_REFNIL;
  632. LuaFunction* function = luaScript_->GetFunction("DestroyScriptObjectInstance");
  633. if (function && function->BeginCall())
  634. {
  635. function->PushUserType((void*)this, "LuaScriptInstance");
  636. function->EndCall();
  637. }
  638. for (int i = 0; i < MAX_LUA_SCRIPT_OBJECT_METHODS; ++i)
  639. scriptObjectMethods_[i] = 0;
  640. }
  641. LuaFunction* LuaScriptInstance::GetScriptObjectFunction(const String& functionName) const
  642. {
  643. return luaScript_->GetFunction(scriptObjectType_ + "." + functionName, true);
  644. }
  645. void LuaScriptInstance::SetScriptFileAttr(const ResourceRef& value)
  646. {
  647. ResourceCache* cache = GetSubsystem<ResourceCache>();
  648. SetScriptFile(cache->GetResource<LuaFile>(value.name_));
  649. }
  650. ResourceRef LuaScriptInstance::GetScriptFileAttr() const
  651. {
  652. return GetResourceRef(scriptFile_, LuaFile::GetTypeStatic());
  653. }
  654. }