ScriptInstance.cpp 29 KB

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