ScriptInstance.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  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 "../Precompiled.h"
  23. #include "../AngelScript/Script.h"
  24. #include "../AngelScript/ScriptFile.h"
  25. #include "../AngelScript/ScriptInstance.h"
  26. #include "../Core/Context.h"
  27. #include "../Core/Profiler.h"
  28. #include "../IO/Log.h"
  29. #include "../IO/MemoryBuffer.h"
  30. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  31. #include "../Physics/PhysicsEvents.h"
  32. #endif
  33. #include "../Resource/ResourceCache.h"
  34. #include "../Resource/ResourceEvents.h"
  35. #include "../Scene/Scene.h"
  36. #include "../Scene/SceneEvents.h"
  37. #include <AngelScript/angelscript.h>
  38. #include "../DebugNew.h"
  39. namespace Urho3D
  40. {
  41. static const char* methodDeclarations[] = {
  42. "void Start()",
  43. "void Stop()",
  44. "void DelayedStart()",
  45. "void Update(float)",
  46. "void PostUpdate(float)",
  47. "void FixedUpdate(float)",
  48. "void FixedPostUpdate(float)",
  49. "void Load(Deserializer&)",
  50. "void Save(Serializer&)",
  51. "void ReadNetworkUpdate(Deserializer&)",
  52. "void WriteNetworkUpdate(Serializer&)",
  53. "void ApplyAttributes()",
  54. "void TransformChanged()"
  55. };
  56. ScriptInstance::ScriptInstance(Context* context) :
  57. Component(context),
  58. scriptObject_(0),
  59. subscribed_(false),
  60. subscribedPostFixed_(false)
  61. {
  62. ClearScriptMethods();
  63. ClearScriptAttributes();
  64. }
  65. ScriptInstance::~ScriptInstance()
  66. {
  67. ReleaseObject();
  68. }
  69. void ScriptInstance::RegisterObject(Context* context)
  70. {
  71. context->RegisterFactory<ScriptInstance>(LOGIC_CATEGORY);
  72. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  73. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Delayed Method Calls", GetDelayedCallsAttr, SetDelayedCallsAttr, PODVector<unsigned char>,
  74. Variant::emptyBuffer, AM_FILE | AM_NOEDIT);
  75. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Script File", GetScriptFileAttr, SetScriptFileAttr, ResourceRef,
  76. ResourceRef(ScriptFile::GetTypeStatic()), AM_DEFAULT);
  77. URHO3D_ACCESSOR_ATTRIBUTE("Class Name", GetClassName, SetClassName, String, String::EMPTY, AM_DEFAULT);
  78. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Script Data", GetScriptDataAttr, SetScriptDataAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  79. AM_FILE | AM_NOEDIT);
  80. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Script Network Data", GetScriptNetworkDataAttr, SetScriptNetworkDataAttr, PODVector<unsigned char>,
  81. Variant::emptyBuffer, AM_NET | AM_NOEDIT);
  82. }
  83. void ScriptInstance::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  84. {
  85. if (attr.mode_ & (AM_NODEID | AM_COMPONENTID))
  86. {
  87. // The component / node to which the ID refers to may not be in the scene yet, and furthermore the ID must go through the
  88. // SceneResolver first. Delay searching for the object to ApplyAttributes
  89. AttributeInfo* attrPtr = const_cast<AttributeInfo*>(&attr);
  90. idAttributes_[attrPtr] = src.GetUInt();
  91. }
  92. else if (attr.type_ == VAR_RESOURCEREF && attr.ptr_)
  93. {
  94. Resource*& resourcePtr = *(reinterpret_cast<Resource**>(attr.ptr_));
  95. // Decrease reference count of the old object if any, then increment the new
  96. if (resourcePtr)
  97. resourcePtr->ReleaseRef();
  98. const ResourceRef& ref = src.GetResourceRef();
  99. resourcePtr = GetSubsystem<ResourceCache>()->GetResource(ref.type_, ref.name_);
  100. if (resourcePtr)
  101. resourcePtr->AddRef();
  102. }
  103. else
  104. Serializable::OnSetAttribute(attr, src);
  105. }
  106. void ScriptInstance::OnGetAttribute(const AttributeInfo& attr, Variant& dest) const
  107. {
  108. AttributeInfo* attrPtr = const_cast<AttributeInfo*>(&attr);
  109. // Get ID's for node / component handle attributes
  110. if (attr.mode_ & (AM_NODEID | AM_COMPONENTID))
  111. {
  112. // If a cached ID value has been stored, return it instead of querying from the actual object
  113. // (the object handle is likely null at that point)
  114. HashMap<AttributeInfo*, unsigned>::ConstIterator i = idAttributes_.Find(attrPtr);
  115. if (i != idAttributes_.End())
  116. dest = i->second_;
  117. else if (attr.mode_ & AM_NODEID)
  118. {
  119. Node* node = *(reinterpret_cast<Node**>(attr.ptr_));
  120. unsigned nodeID = node ? node->GetID() : 0;
  121. dest = nodeID;
  122. }
  123. else
  124. {
  125. Component* component = *(reinterpret_cast<Component**>(attr.ptr_));
  126. unsigned componentID = component ? component->GetID() : 0;
  127. dest = componentID;
  128. }
  129. }
  130. else if (attr.type_ == VAR_RESOURCEREF && attr.ptr_)
  131. {
  132. Resource* resource = *(reinterpret_cast<Resource**>(attr.ptr_));
  133. // If resource is non-null get its type and name hash. Otherwise get type from the default value
  134. dest = GetResourceRef(resource, attr.defaultValue_.GetResourceRef().type_);
  135. }
  136. else
  137. Serializable::OnGetAttribute(attr, dest);
  138. }
  139. void ScriptInstance::ApplyAttributes()
  140. {
  141. // Apply node / component ID attributes now (find objects from the scene and assign to the object handles)
  142. for (HashMap<AttributeInfo*, unsigned>::Iterator i = idAttributes_.Begin(); i != idAttributes_.End(); ++i)
  143. {
  144. AttributeInfo& attr = *i->first_;
  145. if (attr.mode_ & AM_NODEID)
  146. {
  147. Node*& nodePtr = *(reinterpret_cast<Node**>(attr.ptr_));
  148. // Decrease reference count of the old object if any, then increment the new
  149. if (nodePtr)
  150. nodePtr->ReleaseRef();
  151. nodePtr = GetScene()->GetNode(i->second_);
  152. if (nodePtr)
  153. nodePtr->AddRef();
  154. }
  155. else if (attr.mode_ & AM_COMPONENTID)
  156. {
  157. Component*& componentPtr = *(reinterpret_cast<Component**>(attr.ptr_));
  158. if (componentPtr)
  159. componentPtr->ReleaseRef();
  160. componentPtr = GetScene()->GetComponent(i->second_);
  161. if (componentPtr)
  162. componentPtr->AddRef();
  163. }
  164. }
  165. idAttributes_.Clear();
  166. if (scriptObject_ && methods_[METHOD_APPLYATTRIBUTES])
  167. scriptFile_->Execute(scriptObject_, methods_[METHOD_APPLYATTRIBUTES]);
  168. }
  169. void ScriptInstance::OnSetEnabled()
  170. {
  171. UpdateEventSubscription();
  172. }
  173. bool ScriptInstance::CreateObject(ScriptFile* scriptFile, const String& className)
  174. {
  175. className_ = String::EMPTY; // Do not create object during SetScriptFile()
  176. SetScriptFile(scriptFile);
  177. SetClassName(className);
  178. return scriptObject_ != 0;
  179. }
  180. void ScriptInstance::SetScriptFile(ScriptFile* scriptFile)
  181. {
  182. if (scriptFile == scriptFile_ && scriptObject_)
  183. return;
  184. ReleaseObject();
  185. // Unsubscribe from the reload event of previous script file (if any), then subscribe to the new
  186. if (scriptFile_)
  187. {
  188. UnsubscribeFromEvent(scriptFile_, E_RELOADSTARTED);
  189. UnsubscribeFromEvent(scriptFile_, E_RELOADFINISHED);
  190. }
  191. if (scriptFile)
  192. {
  193. SubscribeToEvent(scriptFile, E_RELOADSTARTED, URHO3D_HANDLER(ScriptInstance, HandleScriptFileReload));
  194. SubscribeToEvent(scriptFile, E_RELOADFINISHED, URHO3D_HANDLER(ScriptInstance, HandleScriptFileReloadFinished));
  195. }
  196. scriptFile_ = scriptFile;
  197. CreateObject();
  198. MarkNetworkUpdate();
  199. }
  200. void ScriptInstance::SetClassName(const String& className)
  201. {
  202. if (className == className_ && scriptObject_)
  203. return;
  204. ReleaseObject();
  205. className_ = className;
  206. CreateObject();
  207. MarkNetworkUpdate();
  208. }
  209. bool ScriptInstance::Execute(const String& declaration, const VariantVector& parameters)
  210. {
  211. if (!scriptObject_)
  212. return false;
  213. asIScriptFunction* method = scriptFile_->GetMethod(scriptObject_, declaration);
  214. if (!method)
  215. {
  216. URHO3D_LOGERROR("Method " + declaration + " not found in class " + className_);
  217. return false;
  218. }
  219. return scriptFile_->Execute(scriptObject_, method, parameters);
  220. }
  221. bool ScriptInstance::Execute(asIScriptFunction* method, const VariantVector& parameters)
  222. {
  223. if (!method || !scriptObject_)
  224. return false;
  225. return scriptFile_->Execute(scriptObject_, method, parameters);
  226. }
  227. void ScriptInstance::DelayedExecute(float delay, bool repeat, const String& declaration, const VariantVector& parameters)
  228. {
  229. if (!scriptObject_)
  230. return;
  231. DelayedCall call;
  232. call.period_ = call.delay_ = Max(delay, 0.0f);
  233. call.repeat_ = repeat;
  234. call.declaration_ = declaration;
  235. call.parameters_ = parameters;
  236. delayedCalls_.Push(call);
  237. // Make sure we are registered to the scene update event, because delayed calls are executed there
  238. if (!subscribed_)
  239. UpdateEventSubscription();
  240. }
  241. void ScriptInstance::ClearDelayedExecute(const String& declaration)
  242. {
  243. if (declaration.Empty())
  244. delayedCalls_.Clear();
  245. else
  246. {
  247. for (Vector<DelayedCall>::Iterator i = delayedCalls_.Begin(); i != delayedCalls_.End();)
  248. {
  249. if (declaration == i->declaration_)
  250. i = delayedCalls_.Erase(i);
  251. else
  252. ++i;
  253. }
  254. }
  255. }
  256. void ScriptInstance::AddEventHandler(StringHash eventType, const String& handlerName)
  257. {
  258. if (!scriptObject_)
  259. return;
  260. String declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  261. asIScriptFunction* method = scriptFile_->GetMethod(scriptObject_, declaration);
  262. if (!method)
  263. {
  264. // Retry with parameterless signature
  265. method = scriptFile_->GetMethod(scriptObject_, handlerName);
  266. if (!method)
  267. {
  268. URHO3D_LOGERROR("Event handler method " + handlerName + " not found in " + scriptFile_->GetName());
  269. return;
  270. }
  271. }
  272. SubscribeToEvent(eventType, URHO3D_HANDLER_USERDATA(ScriptInstance, HandleScriptEvent, (void*)method));
  273. }
  274. void ScriptInstance::AddEventHandler(Object* sender, StringHash eventType, const String& handlerName)
  275. {
  276. if (!scriptObject_)
  277. return;
  278. if (!sender)
  279. {
  280. URHO3D_LOGERROR("Null event sender for event " + String(eventType) + ", handler " + handlerName);
  281. return;
  282. }
  283. String declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  284. asIScriptFunction* method = scriptFile_->GetMethod(scriptObject_, declaration);
  285. if (!method)
  286. {
  287. // Retry with parameterless signature
  288. method = scriptFile_->GetMethod(scriptObject_, handlerName);
  289. if (!method)
  290. {
  291. URHO3D_LOGERROR("Event handler method " + handlerName + " not found in " + scriptFile_->GetName());
  292. return;
  293. }
  294. }
  295. SubscribeToEvent(sender, eventType, URHO3D_HANDLER_USERDATA(ScriptInstance, HandleScriptEvent, (void*)method));
  296. }
  297. void ScriptInstance::RemoveEventHandler(StringHash eventType)
  298. {
  299. UnsubscribeFromEvent(eventType);
  300. }
  301. void ScriptInstance::RemoveEventHandler(Object* sender, StringHash eventType)
  302. {
  303. UnsubscribeFromEvent(sender, eventType);
  304. }
  305. void ScriptInstance::RemoveEventHandlers(Object* sender)
  306. {
  307. UnsubscribeFromEvents(sender);
  308. }
  309. void ScriptInstance::RemoveEventHandlers()
  310. {
  311. UnsubscribeFromAllEventsExcept(PODVector<StringHash>(), true);
  312. }
  313. void ScriptInstance::RemoveEventHandlersExcept(const PODVector<StringHash>& exceptions)
  314. {
  315. UnsubscribeFromAllEventsExcept(exceptions, true);
  316. }
  317. bool ScriptInstance::HasEventHandler(StringHash eventType) const
  318. {
  319. return HasSubscribedToEvent(eventType);
  320. }
  321. bool ScriptInstance::HasEventHandler(Object* sender, StringHash eventType) const
  322. {
  323. return HasSubscribedToEvent(sender, eventType);
  324. }
  325. bool ScriptInstance::IsA(const String& className) const
  326. {
  327. // Early out for the easiest case where that's what we are
  328. if (className_ == className)
  329. return true;
  330. if (scriptObject_)
  331. {
  332. // Start immediately at the first base class because we already checked the early out
  333. asIObjectType* currentType = scriptObject_->GetObjectType()->GetBaseType();
  334. while (currentType)
  335. {
  336. if (className == currentType->GetName())
  337. return true;
  338. currentType = currentType->GetBaseType();
  339. }
  340. }
  341. return false;
  342. }
  343. bool ScriptInstance::HasMethod(const String& declaration) const
  344. {
  345. if (!scriptFile_ || !scriptObject_)
  346. return false;
  347. else
  348. return scriptFile_->GetMethod(scriptObject_, declaration) != 0;
  349. }
  350. void ScriptInstance::SetScriptFileAttr(const ResourceRef& value)
  351. {
  352. ResourceCache* cache = GetSubsystem<ResourceCache>();
  353. SetScriptFile(cache->GetResource<ScriptFile>(value.name_));
  354. }
  355. void ScriptInstance::SetDelayedCallsAttr(const PODVector<unsigned char>& value)
  356. {
  357. MemoryBuffer buf(value);
  358. delayedCalls_.Resize(buf.ReadVLE());
  359. for (Vector<DelayedCall>::Iterator i = delayedCalls_.Begin(); i != delayedCalls_.End(); ++i)
  360. {
  361. i->period_ = buf.ReadFloat();
  362. i->delay_ = buf.ReadFloat();
  363. i->repeat_ = buf.ReadBool();
  364. i->declaration_ = buf.ReadString();
  365. i->parameters_ = buf.ReadVariantVector();
  366. }
  367. if (scriptObject_ && delayedCalls_.Size() && !subscribed_)
  368. UpdateEventSubscription();
  369. }
  370. void ScriptInstance::SetScriptDataAttr(const PODVector<unsigned char>& data)
  371. {
  372. if (scriptObject_ && methods_[METHOD_LOAD])
  373. {
  374. MemoryBuffer buf(data);
  375. VariantVector parameters;
  376. parameters.Push(Variant((void*)static_cast<Deserializer*>(&buf)));
  377. scriptFile_->Execute(scriptObject_, methods_[METHOD_LOAD], parameters);
  378. }
  379. }
  380. void ScriptInstance::SetScriptNetworkDataAttr(const PODVector<unsigned char>& data)
  381. {
  382. if (scriptObject_ && methods_[METHOD_READNETWORKUPDATE])
  383. {
  384. MemoryBuffer buf(data);
  385. VariantVector parameters;
  386. parameters.Push(Variant((void*)static_cast<Deserializer*>(&buf)));
  387. scriptFile_->Execute(scriptObject_, methods_[METHOD_READNETWORKUPDATE], parameters);
  388. }
  389. }
  390. ResourceRef ScriptInstance::GetScriptFileAttr() const
  391. {
  392. return GetResourceRef(scriptFile_, ScriptFile::GetTypeStatic());
  393. }
  394. PODVector<unsigned char> ScriptInstance::GetDelayedCallsAttr() const
  395. {
  396. VectorBuffer buf;
  397. buf.WriteVLE(delayedCalls_.Size());
  398. for (Vector<DelayedCall>::ConstIterator i = delayedCalls_.Begin(); i != delayedCalls_.End(); ++i)
  399. {
  400. buf.WriteFloat(i->period_);
  401. buf.WriteFloat(i->delay_);
  402. buf.WriteBool(i->repeat_);
  403. buf.WriteString(i->declaration_);
  404. buf.WriteVariantVector(i->parameters_);
  405. }
  406. return buf.GetBuffer();
  407. }
  408. PODVector<unsigned char> ScriptInstance::GetScriptDataAttr() const
  409. {
  410. if (!scriptObject_ || !methods_[METHOD_SAVE])
  411. return PODVector<unsigned char>();
  412. else
  413. {
  414. VectorBuffer buf;
  415. VariantVector parameters;
  416. parameters.Push(Variant((void*)static_cast<Serializer*>(&buf)));
  417. scriptFile_->Execute(scriptObject_, methods_[METHOD_SAVE], parameters);
  418. return buf.GetBuffer();
  419. }
  420. }
  421. PODVector<unsigned char> ScriptInstance::GetScriptNetworkDataAttr() const
  422. {
  423. if (!scriptObject_ || !methods_[METHOD_WRITENETWORKUPDATE])
  424. return PODVector<unsigned char>();
  425. else
  426. {
  427. VectorBuffer buf;
  428. VariantVector parameters;
  429. parameters.Push(Variant((void*)static_cast<Serializer*>(&buf)));
  430. scriptFile_->Execute(scriptObject_, methods_[METHOD_WRITENETWORKUPDATE], parameters);
  431. return buf.GetBuffer();
  432. }
  433. }
  434. void ScriptInstance::OnSceneSet(Scene* scene)
  435. {
  436. if (scene)
  437. UpdateEventSubscription();
  438. else
  439. {
  440. UnsubscribeFromEvent(E_SCENEUPDATE);
  441. UnsubscribeFromEvent(E_SCENEPOSTUPDATE);
  442. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  443. UnsubscribeFromEvent(E_PHYSICSPRESTEP);
  444. UnsubscribeFromEvent(E_PHYSICSPOSTSTEP);
  445. #endif
  446. subscribed_ = false;
  447. subscribedPostFixed_ = false;
  448. }
  449. }
  450. void ScriptInstance::OnMarkedDirty(Node* node)
  451. {
  452. // Script functions are not safe from worker threads
  453. Scene* scene = GetScene();
  454. if (scene && scene->IsThreadedUpdate())
  455. {
  456. scene->DelayedMarkedDirty(this);
  457. return;
  458. }
  459. if (scriptObject_ && methods_[METHOD_TRANSFORMCHANGED])
  460. scriptFile_->Execute(scriptObject_, methods_[METHOD_TRANSFORMCHANGED]);
  461. }
  462. void ScriptInstance::CreateObject()
  463. {
  464. if (!scriptFile_ || className_.Empty())
  465. return;
  466. URHO3D_PROFILE(CreateScriptObject);
  467. scriptObject_ = scriptFile_->CreateObject(className_);
  468. if (scriptObject_)
  469. {
  470. // Map script object to script instance with userdata
  471. scriptObject_->SetUserData(this);
  472. GetScriptMethods();
  473. GetScriptAttributes();
  474. UpdateEventSubscription();
  475. if (methods_[METHOD_START])
  476. scriptFile_->Execute(scriptObject_, methods_[METHOD_START]);
  477. }
  478. else
  479. URHO3D_LOGERROR("Failed to create object of class " + className_ + " from " + scriptFile_->GetName());
  480. }
  481. void ScriptInstance::ReleaseObject()
  482. {
  483. if (scriptObject_)
  484. {
  485. if (methods_[METHOD_STOP])
  486. scriptFile_->Execute(scriptObject_, methods_[METHOD_STOP]);
  487. PODVector<StringHash> exceptions;
  488. exceptions.Push(E_RELOADSTARTED);
  489. exceptions.Push(E_RELOADFINISHED);
  490. UnsubscribeFromAllEventsExcept(exceptions, false);
  491. if (node_)
  492. node_->RemoveListener(this);
  493. subscribed_ = false;
  494. subscribedPostFixed_ = false;
  495. ClearScriptMethods();
  496. ClearScriptAttributes();
  497. scriptObject_->SetUserData(0);
  498. scriptObject_->Release();
  499. scriptObject_ = 0;
  500. }
  501. }
  502. void ScriptInstance::ClearScriptMethods()
  503. {
  504. for (unsigned i = 0; i < MAX_SCRIPT_METHODS; ++i)
  505. methods_[i] = 0;
  506. delayedCalls_.Clear();
  507. }
  508. void ScriptInstance::ClearScriptAttributes()
  509. {
  510. attributeInfos_ = *context_->GetAttributes(GetTypeStatic());
  511. idAttributes_.Clear();
  512. }
  513. void ScriptInstance::GetScriptMethods()
  514. {
  515. for (unsigned i = 0; i < MAX_SCRIPT_METHODS; ++i)
  516. methods_[i] = scriptFile_->GetMethod(scriptObject_, methodDeclarations[i]);
  517. }
  518. void ScriptInstance::GetScriptAttributes()
  519. {
  520. asIScriptEngine* engine = GetSubsystem<Script>()->GetScriptEngine();
  521. attributeInfos_ = *context_->GetAttributes(GetTypeStatic());
  522. unsigned numProperties = scriptObject_->GetPropertyCount();
  523. for (unsigned i = 0; i < numProperties; ++i)
  524. {
  525. const char* name;
  526. int typeId;
  527. bool isPrivate, isProtected, isHandle;
  528. scriptObject_->GetObjectType()->GetProperty(i, &name, &typeId, &isPrivate, &isProtected);
  529. // Hide private variables or ones that begin with an underscore
  530. if (isPrivate || isProtected || name[0] == '_')
  531. continue;
  532. String typeName = engine->GetTypeDeclaration(typeId);
  533. isHandle = typeName.EndsWith("@");
  534. if (isHandle)
  535. typeName = typeName.Substring(0, typeName.Length() - 1);
  536. AttributeInfo info;
  537. info.mode_ = AM_FILE;
  538. info.name_ = name;
  539. info.ptr_ = scriptObject_->GetAddressOfProperty(i);
  540. if (!isHandle)
  541. {
  542. switch (typeId)
  543. {
  544. case asTYPEID_BOOL:
  545. info.type_ = VAR_BOOL;
  546. break;
  547. case asTYPEID_INT32:
  548. case asTYPEID_UINT32:
  549. info.type_ = VAR_INT;
  550. break;
  551. case asTYPEID_FLOAT:
  552. info.type_ = VAR_FLOAT;
  553. break;
  554. default:
  555. info.type_ = Variant::GetTypeFromName(typeName);
  556. break;
  557. }
  558. }
  559. else
  560. {
  561. // For a handle type, check if it's an Object subclass with a registered factory
  562. StringHash typeHash(typeName);
  563. const HashMap<StringHash, SharedPtr<ObjectFactory> >& factories = context_->GetObjectFactories();
  564. HashMap<StringHash, SharedPtr<ObjectFactory> >::ConstIterator j = factories.Find(typeHash);
  565. if (j != factories.End())
  566. {
  567. // Check base class type. Node & Component are supported as ID attributes, Resource as a resource reference
  568. const TypeInfo* typeInfo = j->second_->GetTypeInfo();
  569. if (typeInfo->IsTypeOf<Node>())
  570. {
  571. info.mode_ |= AM_NODEID;
  572. info.type_ = VAR_INT;
  573. }
  574. else if (typeInfo->IsTypeOf<Component>())
  575. {
  576. info.mode_ |= AM_COMPONENTID;
  577. info.type_ = VAR_INT;
  578. }
  579. else if (typeInfo->IsTypeOf<Resource>())
  580. {
  581. info.type_ = VAR_RESOURCEREF;
  582. info.defaultValue_ = ResourceRef(typeHash);
  583. }
  584. }
  585. }
  586. if (info.type_ != VAR_NONE)
  587. attributeInfos_.Push(info);
  588. }
  589. }
  590. void ScriptInstance::UpdateEventSubscription()
  591. {
  592. Scene* scene = GetScene();
  593. if (!scene)
  594. {
  595. URHO3D_LOGWARNING("Node is detached from scene, can not subscribe script object to update events");
  596. return;
  597. }
  598. bool enabled = scriptObject_ && IsEnabledEffective();
  599. if (enabled)
  600. {
  601. if (!subscribed_ && (methods_[METHOD_UPDATE] || methods_[METHOD_DELAYEDSTART] || delayedCalls_.Size()))
  602. {
  603. SubscribeToEvent(scene, E_SCENEUPDATE, URHO3D_HANDLER(ScriptInstance, HandleSceneUpdate));
  604. subscribed_ = true;
  605. }
  606. if (!subscribedPostFixed_)
  607. {
  608. if (methods_[METHOD_POSTUPDATE])
  609. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, URHO3D_HANDLER(ScriptInstance, HandleScenePostUpdate));
  610. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  611. if (methods_[METHOD_FIXEDUPDATE] || methods_[METHOD_FIXEDPOSTUPDATE])
  612. {
  613. Component* world = GetFixedUpdateSource();
  614. if (world)
  615. {
  616. if (methods_[METHOD_FIXEDUPDATE])
  617. SubscribeToEvent(world, E_PHYSICSPRESTEP, URHO3D_HANDLER(ScriptInstance, HandlePhysicsPreStep));
  618. if (methods_[METHOD_FIXEDPOSTUPDATE])
  619. SubscribeToEvent(world, E_PHYSICSPOSTSTEP, URHO3D_HANDLER(ScriptInstance, HandlePhysicsPostStep));
  620. }
  621. else
  622. URHO3D_LOGERROR("No physics world, can not subscribe script object to fixed update events");
  623. }
  624. #endif
  625. subscribedPostFixed_ = true;
  626. }
  627. if (methods_[METHOD_TRANSFORMCHANGED])
  628. node_->AddListener(this);
  629. }
  630. else
  631. {
  632. if (subscribed_)
  633. {
  634. UnsubscribeFromEvent(scene, E_SCENEUPDATE);
  635. subscribed_ = false;
  636. }
  637. if (subscribedPostFixed_)
  638. {
  639. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  640. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  641. Component* world = GetFixedUpdateSource();
  642. if (world)
  643. {
  644. UnsubscribeFromEvent(world, E_PHYSICSPRESTEP);
  645. UnsubscribeFromEvent(world, E_PHYSICSPOSTSTEP);
  646. }
  647. #endif
  648. subscribedPostFixed_ = false;
  649. }
  650. if (methods_[METHOD_TRANSFORMCHANGED])
  651. node_->RemoveListener(this);
  652. }
  653. }
  654. void ScriptInstance::HandleSceneUpdate(StringHash eventType, VariantMap& eventData)
  655. {
  656. if (!scriptObject_)
  657. return;
  658. using namespace SceneUpdate;
  659. float timeStep = eventData[P_TIMESTEP].GetFloat();
  660. // Execute delayed calls
  661. for (unsigned i = 0; i < delayedCalls_.Size();)
  662. {
  663. DelayedCall& call = delayedCalls_[i];
  664. bool remove = false;
  665. call.delay_ -= timeStep;
  666. if (call.delay_ <= 0.0f)
  667. {
  668. if (!call.repeat_)
  669. remove = true;
  670. else
  671. call.delay_ += call.period_;
  672. Execute(call.declaration_, call.parameters_);
  673. }
  674. if (remove)
  675. delayedCalls_.Erase(i);
  676. else
  677. ++i;
  678. }
  679. // Execute delayed start before first update
  680. if (methods_[METHOD_DELAYEDSTART])
  681. {
  682. scriptFile_->Execute(scriptObject_, methods_[METHOD_DELAYEDSTART]);
  683. methods_[METHOD_DELAYEDSTART] = 0; // Only execute once
  684. }
  685. if (methods_[METHOD_UPDATE])
  686. {
  687. VariantVector parameters;
  688. parameters.Push(timeStep);
  689. scriptFile_->Execute(scriptObject_, methods_[METHOD_UPDATE], parameters);
  690. }
  691. }
  692. void ScriptInstance::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  693. {
  694. if (!scriptObject_)
  695. return;
  696. using namespace ScenePostUpdate;
  697. VariantVector parameters;
  698. parameters.Push(eventData[P_TIMESTEP]);
  699. scriptFile_->Execute(scriptObject_, methods_[METHOD_POSTUPDATE], parameters);
  700. }
  701. #if defined(URHO3D_PHYSICS) || defined(URHO3D_URHO2D)
  702. void ScriptInstance::HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData)
  703. {
  704. if (!scriptObject_)
  705. return;
  706. using namespace PhysicsPreStep;
  707. VariantVector parameters;
  708. parameters.Push(eventData[P_TIMESTEP]);
  709. scriptFile_->Execute(scriptObject_, methods_[METHOD_FIXEDUPDATE], parameters);
  710. }
  711. void ScriptInstance::HandlePhysicsPostStep(StringHash eventType, VariantMap& eventData)
  712. {
  713. if (!scriptObject_)
  714. return;
  715. using namespace PhysicsPostStep;
  716. VariantVector parameters;
  717. parameters.Push(eventData[P_TIMESTEP]);
  718. scriptFile_->Execute(scriptObject_, methods_[METHOD_FIXEDPOSTUPDATE], parameters);
  719. }
  720. #endif
  721. void ScriptInstance::HandleScriptEvent(StringHash eventType, VariantMap& eventData)
  722. {
  723. if (!IsEnabledEffective() || !scriptFile_ || !scriptObject_)
  724. return;
  725. asIScriptFunction* method = static_cast<asIScriptFunction*>(GetEventHandler()->GetUserData());
  726. VariantVector parameters;
  727. if (method->GetParamCount() > 0)
  728. {
  729. parameters.Push(Variant((void*)&eventType));
  730. parameters.Push(Variant((void*)&eventData));
  731. }
  732. scriptFile_->Execute(scriptObject_, method, parameters);
  733. }
  734. void ScriptInstance::HandleScriptFileReload(StringHash eventType, VariantMap& eventData)
  735. {
  736. ReleaseObject();
  737. }
  738. void ScriptInstance::HandleScriptFileReloadFinished(StringHash eventType, VariantMap& eventData)
  739. {
  740. if (!className_.Empty())
  741. CreateObject();
  742. }
  743. Context* GetScriptContext()
  744. {
  745. return static_cast<Script*>(asGetActiveContext()->GetEngine()->GetUserData())->GetContext();
  746. }
  747. ScriptInstance* GetScriptContextInstance()
  748. {
  749. asIScriptContext* context = asGetActiveContext();
  750. asIScriptObject* object = context ? static_cast<asIScriptObject*>(context->GetThisPointer()) : 0;
  751. if (object)
  752. return static_cast<ScriptInstance*>(object->GetUserData());
  753. else
  754. return 0;
  755. }
  756. Node* GetScriptContextNode()
  757. {
  758. ScriptInstance* instance = GetScriptContextInstance();
  759. return instance ? instance->GetNode() : 0;
  760. }
  761. Scene* GetScriptContextScene()
  762. {
  763. Scene* scene = 0;
  764. Node* node = GetScriptContextNode();
  765. if (node)
  766. scene = node->GetScene();
  767. // If null, try to get the default scene
  768. if (!scene)
  769. scene = GetScriptContext()->GetSubsystem<Script>()->GetDefaultScene();
  770. return scene;
  771. }
  772. ScriptEventListener* GetScriptContextEventListener()
  773. {
  774. // If the context has an object and that object has user data set, try and get the ScriptInstance, otherwise try and get a ScriptFile.
  775. asIScriptContext* context = asGetActiveContext();
  776. if (context)
  777. {
  778. asIScriptObject* object = static_cast<asIScriptObject*>(context->GetThisPointer());
  779. if (object && object->GetUserData())
  780. return GetScriptContextInstance();
  781. else
  782. return GetScriptContextFile();
  783. }
  784. else
  785. return 0;
  786. }
  787. Object* GetScriptContextEventListenerObject()
  788. {
  789. return dynamic_cast<Object*>(GetScriptContextEventListener());
  790. }
  791. }