ScriptFile.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  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 "ArrayPtr.h"
  24. #include "Context.h"
  25. #include "CoreEvents.h"
  26. #include "FileSystem.h"
  27. #include "Log.h"
  28. #include "Profiler.h"
  29. #include "ResourceCache.h"
  30. #include "Script.h"
  31. #include "ScriptFile.h"
  32. #include "ScriptInstance.h"
  33. #include <angelscript.h>
  34. #include <cstring>
  35. #include "DebugNew.h"
  36. namespace Urho3D
  37. {
  38. /// Helper class for saving AngelScript bytecode.
  39. class ByteCodeSerializer : public asIBinaryStream
  40. {
  41. public:
  42. /// Construct.
  43. ByteCodeSerializer(Serializer& dest) :
  44. dest_(dest)
  45. {
  46. }
  47. /// Read from stream (no-op).
  48. virtual void Read(void* ptr, asUINT size)
  49. {
  50. // No-op, can not read from a Serializer
  51. }
  52. /// Write to stream.
  53. virtual void Write(const void* ptr, asUINT size)
  54. {
  55. dest_.Write(ptr, size);
  56. }
  57. private:
  58. /// Destination stream.
  59. Serializer& dest_;
  60. };
  61. /// Helper class for loading AngelScript bytecode.
  62. class ByteCodeDeserializer : public asIBinaryStream
  63. {
  64. public:
  65. /// Construct.
  66. ByteCodeDeserializer(Deserializer& source) :
  67. source_(source)
  68. {
  69. }
  70. /// Read from stream.
  71. virtual void Read(void* ptr, asUINT size)
  72. {
  73. source_.Read(ptr, size);
  74. }
  75. /// Write to stream (no-op).
  76. virtual void Write(const void* ptr, asUINT size)
  77. {
  78. }
  79. private:
  80. /// Source stream.
  81. Deserializer& source_;
  82. };
  83. ScriptFile::ScriptFile(Context* context) :
  84. Resource(context),
  85. script_(GetSubsystem<Script>()),
  86. scriptModule_(0),
  87. compiled_(false),
  88. subscribed_(false)
  89. {
  90. }
  91. ScriptFile::~ScriptFile()
  92. {
  93. ReleaseModule();
  94. }
  95. void ScriptFile::RegisterObject(Context* context)
  96. {
  97. context->RegisterFactory<ScriptFile>();
  98. }
  99. bool ScriptFile::Load(Deserializer& source)
  100. {
  101. PROFILE(LoadScript);
  102. ReleaseModule();
  103. // Create the module. Discard previous module if there was one
  104. asIScriptEngine* engine = script_->GetScriptEngine();
  105. scriptModule_ = engine->GetModule(GetName().CString(), asGM_ALWAYS_CREATE);
  106. if (!scriptModule_)
  107. {
  108. LOGERROR("Failed to create script module " + GetName());
  109. return false;
  110. }
  111. // Check if this file is precompiled bytecode
  112. if (source.ReadFileID() == "ASBC")
  113. {
  114. ByteCodeDeserializer deserializer = ByteCodeDeserializer(source);
  115. if (scriptModule_->LoadByteCode(&deserializer) >= 0)
  116. {
  117. LOGINFO("Loaded script module " + GetName() + " from bytecode");
  118. compiled_ = true;
  119. // Map script module to script resource with userdata
  120. scriptModule_->SetUserData(this);
  121. return true;
  122. }
  123. else
  124. return false;
  125. }
  126. else
  127. source.Seek(0);
  128. // Not bytecode: add the initial section and check for includes
  129. if (!AddScriptSection(engine, source))
  130. return false;
  131. // Compile
  132. int result = scriptModule_->Build();
  133. if (result < 0)
  134. {
  135. LOGERROR("Failed to compile script module " + GetName());
  136. return false;
  137. }
  138. LOGINFO("Compiled script module " + GetName());
  139. compiled_ = true;
  140. // Map script module to script resource with userdata
  141. scriptModule_->SetUserData(this);
  142. return true;
  143. }
  144. void ScriptFile::AddEventHandler(StringHash eventType, const String& handlerName)
  145. {
  146. if (!compiled_)
  147. return;
  148. String declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  149. asIScriptFunction* function = 0;
  150. asIScriptObject* reciever = static_cast<asIScriptObject*>(asGetActiveContext()->GetThisPointer());
  151. if (reciever)
  152. function = GetMethod(reciever, declaration);
  153. else
  154. function = GetFunction(declaration);
  155. if (!function)
  156. {
  157. declaration = "void " + handlerName + "()";
  158. if (reciever)
  159. function = GetMethod(reciever, declaration);
  160. else
  161. function = GetFunction(declaration);
  162. if (!function)
  163. {
  164. LOGERROR("Event handler function " + handlerName + " not found in " + GetName());
  165. return;
  166. }
  167. }
  168. SharedPtr<ScriptEventData> data(new ScriptEventData(function, reciever));
  169. scriptEventData_.Push(data);
  170. SubscribeToEvent(eventType, HANDLER_USERDATA(ScriptFile, HandleScriptEvent, data.Get()));
  171. }
  172. void ScriptFile::AddEventHandler(Object* sender, StringHash eventType, const String& handlerName)
  173. {
  174. if (!compiled_)
  175. return;
  176. if (!sender)
  177. {
  178. LOGERROR("Null event sender for event " + String(eventType) + ", handler " + handlerName);
  179. return;
  180. }
  181. String declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  182. asIScriptFunction* function = 0;
  183. asIScriptObject* reciever = static_cast<asIScriptObject*>(asGetActiveContext()->GetThisPointer());
  184. if (reciever)
  185. function = GetMethod(reciever, declaration);
  186. else
  187. function = GetFunction(declaration);
  188. if (!function)
  189. {
  190. declaration = "void " + handlerName + "()";
  191. if (reciever)
  192. function = GetMethod(reciever, declaration);
  193. else
  194. function = GetFunction(declaration);
  195. if (!function)
  196. {
  197. LOGERROR("Event handler function " + handlerName + " not found in " + GetName());
  198. return;
  199. }
  200. }
  201. SharedPtr<ScriptEventData> data(new ScriptEventData(function, reciever));
  202. scriptEventData_.Push(data);
  203. SubscribeToEvent(sender, eventType, HANDLER_USERDATA(ScriptFile, HandleScriptEvent, data.Get()));
  204. }
  205. bool ScriptFile::Execute(const String& declaration, const VariantVector& parameters, bool unprepare)
  206. {
  207. asIScriptFunction* function = GetFunction(declaration);
  208. if (!function)
  209. {
  210. LOGERROR("Function " + declaration + " not found in " + GetName());
  211. return false;
  212. }
  213. return Execute(function, parameters, unprepare);
  214. }
  215. bool ScriptFile::Execute(asIScriptFunction* function, const VariantVector& parameters, bool unprepare)
  216. {
  217. PROFILE(ExecuteFunction);
  218. if (!compiled_ || !function)
  219. return false;
  220. // It is possible that executing the function causes us to unload. Therefore do not rely on member variables
  221. // However, we are not prepared for the whole script system getting destroyed during execution (should never happen)
  222. Script* scriptSystem = script_;
  223. asIScriptContext* context = scriptSystem->GetScriptFileContext();
  224. if (context->Prepare(function) < 0)
  225. return false;
  226. SetParameters(context, function, parameters);
  227. scriptSystem->IncScriptNestingLevel();
  228. bool success = context->Execute() >= 0;
  229. if (unprepare)
  230. context->Unprepare();
  231. scriptSystem->DecScriptNestingLevel();
  232. return success;
  233. }
  234. bool ScriptFile::Execute(asIScriptObject* object, const String& declaration, const VariantVector& parameters, bool unprepare)
  235. {
  236. asIScriptFunction* method = GetMethod(object, declaration);
  237. if (!method)
  238. {
  239. LOGERROR("Method " + declaration + " not found in " + GetName());
  240. return false;
  241. }
  242. return Execute(object, method, parameters, unprepare);
  243. }
  244. bool ScriptFile::Execute(asIScriptObject* object, asIScriptFunction* method, const VariantVector& parameters, bool unprepare)
  245. {
  246. PROFILE(ExecuteMethod);
  247. if (!compiled_ || !object || !method)
  248. return false;
  249. // It is possible that executing the method causes us to unload. Therefore do not rely on member variables
  250. // However, we are not prepared for the whole script system getting destroyed during execution (should never happen)
  251. Script* scriptSystem = script_;
  252. asIScriptContext* context = scriptSystem->GetScriptFileContext();
  253. if (context->Prepare(method) < 0)
  254. return false;
  255. context->SetObject(object);
  256. SetParameters(context, method, parameters);
  257. scriptSystem->IncScriptNestingLevel();
  258. bool success = context->Execute() >= 0;
  259. if (unprepare)
  260. context->Unprepare();
  261. scriptSystem->DecScriptNestingLevel();
  262. return success;
  263. }
  264. void ScriptFile::DelayedExecute(float delay, bool repeat, const String& declaration, const VariantVector& parameters)
  265. {
  266. DelayedCall call;
  267. call.period_ = call.delay_ = Max(delay, 0.0f);
  268. call.repeat_ = repeat;
  269. call.declaration_ = declaration;
  270. call.parameters_ = parameters;
  271. delayedCalls_.Push(call);
  272. // Make sure we are registered to the application update event, because delayed calls are executed there
  273. if (!subscribed_)
  274. {
  275. SubscribeToEvent(E_UPDATE, HANDLER(ScriptFile, HandleUpdate));
  276. subscribed_ = true;
  277. }
  278. }
  279. void ScriptFile::ClearDelayedExecute(const String& declaration)
  280. {
  281. if (declaration.Empty())
  282. delayedCalls_.Clear();
  283. else
  284. {
  285. for (Vector<DelayedCall>::Iterator i = delayedCalls_.Begin(); i != delayedCalls_.End();)
  286. {
  287. if (declaration == i->declaration_)
  288. i = delayedCalls_.Erase(i);
  289. else
  290. ++i;
  291. }
  292. }
  293. }
  294. asIScriptObject* ScriptFile::CreateObject(const String& className)
  295. {
  296. PROFILE(CreateObject);
  297. if (!compiled_)
  298. return 0;
  299. asIScriptContext* context = script_->GetScriptFileContext();
  300. asIScriptEngine* engine = script_->GetScriptEngine();
  301. asIObjectType *type = engine->GetObjectTypeById(scriptModule_->GetTypeIdByDecl(className.CString()));
  302. if (!type)
  303. return 0;
  304. // Ensure that the type implements the "ScriptObject" interface, so it can be returned to script properly
  305. bool found = false;
  306. HashMap<asIObjectType*, bool>::ConstIterator i = validClasses_.Find(type);
  307. if (i != validClasses_.End())
  308. found = i->second_;
  309. else
  310. {
  311. unsigned numInterfaces = type->GetInterfaceCount();
  312. for (unsigned j = 0; j < numInterfaces; ++j)
  313. {
  314. asIObjectType* interfaceType = type->GetInterface(j);
  315. if (!strcmp(interfaceType->GetName(), "ScriptObject"))
  316. {
  317. found = true;
  318. break;
  319. }
  320. }
  321. validClasses_[type] = found;
  322. }
  323. if (!found)
  324. {
  325. LOGERROR("Script class " + className + " does not implement the ScriptObject interface");
  326. return 0;
  327. }
  328. // Get the factory function id from the object type
  329. String factoryName = className + "@ " + className + "()";
  330. asIScriptFunction* factory = type->GetFactoryByDecl(factoryName.CString());
  331. if (!factory || context->Prepare(factory) < 0 || context->Execute() < 0)
  332. return 0;
  333. asIScriptObject* obj = *(static_cast<asIScriptObject**>(context->GetAddressOfReturnValue()));
  334. if (obj)
  335. obj->AddRef();
  336. return obj;
  337. }
  338. bool ScriptFile::SaveByteCode(Serializer& dest)
  339. {
  340. if (compiled_)
  341. {
  342. dest.WriteFileID("ASBC");
  343. ByteCodeSerializer serializer = ByteCodeSerializer(dest);
  344. return scriptModule_->SaveByteCode(&serializer, true) >= 0;
  345. }
  346. else
  347. return false;
  348. }
  349. asIScriptFunction* ScriptFile::GetFunction(const String& declaration)
  350. {
  351. if (!compiled_)
  352. return 0;
  353. HashMap<String, asIScriptFunction*>::ConstIterator i = functions_.Find(declaration);
  354. if (i != functions_.End())
  355. return i->second_;
  356. asIScriptFunction* function = scriptModule_->GetFunctionByDecl(declaration.CString());
  357. functions_[declaration] = function;
  358. return function;
  359. }
  360. asIScriptFunction* ScriptFile::GetMethod(asIScriptObject* object, const String& declaration)
  361. {
  362. if (!compiled_ || !object)
  363. return 0;
  364. asIObjectType* type = object->GetObjectType();
  365. if (!type)
  366. return 0;
  367. HashMap<asIObjectType*, HashMap<String, asIScriptFunction*> >::ConstIterator i = methods_.Find(type);
  368. if (i != methods_.End())
  369. {
  370. HashMap<String, asIScriptFunction*>::ConstIterator j = i->second_.Find(declaration);
  371. if (j != i->second_.End())
  372. return j->second_;
  373. }
  374. asIScriptFunction* function = type->GetMethodByDecl(declaration.CString());
  375. methods_[type][declaration] = function;
  376. return function;
  377. }
  378. bool ScriptFile::AddScriptSection(asIScriptEngine* engine, Deserializer& source)
  379. {
  380. ResourceCache* cache = GetSubsystem<ResourceCache>();
  381. unsigned dataSize = source.GetSize();
  382. SharedArrayPtr<char> buffer(new char[dataSize]);
  383. source.Read((void*)buffer.Get(), dataSize);
  384. // Pre-parse for includes
  385. // Adapted from Angelscript's scriptbuilder add-on
  386. Vector<String> includeFiles;
  387. unsigned pos = 0;
  388. while(pos < dataSize)
  389. {
  390. int len;
  391. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  392. if (t == asTC_COMMENT || t == asTC_WHITESPACE)
  393. {
  394. pos += len;
  395. continue;
  396. }
  397. // Is this a preprocessor directive?
  398. if (buffer[pos] == '#')
  399. {
  400. int start = pos++;
  401. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  402. if (t == asTC_IDENTIFIER)
  403. {
  404. String token(&buffer[pos], len);
  405. if (token == "include")
  406. {
  407. pos += len;
  408. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  409. if (t == asTC_WHITESPACE)
  410. {
  411. pos += len;
  412. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  413. }
  414. if (t == asTC_VALUE && len > 2 && buffer[pos] == '"')
  415. {
  416. // Get the include file
  417. String includeFile(&buffer[pos+1], len - 2);
  418. pos += len;
  419. // If the file is not found as it is, add the path of current file but only if it is found there
  420. if (!cache->Exists(includeFile))
  421. {
  422. String prefixedIncludeFile = GetPath(GetName()) + includeFile;
  423. if (cache->Exists(prefixedIncludeFile))
  424. includeFile = prefixedIncludeFile;
  425. }
  426. String includeFileLower = includeFile.ToLower();
  427. // If not included yet, store it for later processing
  428. if (!includeFiles_.Contains(includeFileLower))
  429. {
  430. includeFiles_.Insert(includeFileLower);
  431. includeFiles.Push(includeFile);
  432. }
  433. // Overwrite the include directive with space characters to avoid compiler error
  434. memset(&buffer[start], ' ', pos - start);
  435. }
  436. }
  437. }
  438. }
  439. // Don't search includes within statement blocks or between tokens in statements
  440. else
  441. {
  442. int len;
  443. // Skip until ; or { whichever comes first
  444. while (pos < dataSize && buffer[pos] != ';' && buffer[pos] != '{')
  445. {
  446. engine->ParseToken(&buffer[pos], 0, &len);
  447. pos += len;
  448. }
  449. // Skip entire statement block
  450. if (pos < dataSize && buffer[pos] == '{')
  451. {
  452. ++pos;
  453. // Find the end of the statement block
  454. int level = 1;
  455. while (level > 0 && pos < dataSize)
  456. {
  457. asETokenClass t = engine->ParseToken(&buffer[pos], 0, &len);
  458. if (t == asTC_KEYWORD)
  459. {
  460. if (buffer[pos] == '{')
  461. ++level;
  462. else if(buffer[pos] == '}')
  463. --level;
  464. }
  465. pos += len;
  466. }
  467. }
  468. else
  469. ++pos;
  470. }
  471. }
  472. // Process includes first
  473. for (unsigned i = 0; i < includeFiles.Size(); ++i)
  474. {
  475. cache->StoreResourceDependency(this, includeFiles[i]);
  476. SharedPtr<File> file = cache->GetFile(includeFiles[i]);
  477. if (file)
  478. {
  479. if (!AddScriptSection(engine, *file))
  480. return false;
  481. }
  482. else
  483. {
  484. LOGERROR("Could not process all the include directives in " + GetName() + ": missing " + includeFiles[i]);
  485. return false;
  486. }
  487. }
  488. // Then add this section
  489. if (scriptModule_->AddScriptSection(source.GetName().CString(), (const char*)buffer.Get(), dataSize) < 0)
  490. {
  491. LOGERROR("Failed to add script section " + source.GetName());
  492. return false;
  493. }
  494. SetMemoryUse(GetMemoryUse() + dataSize);
  495. return true;
  496. }
  497. void ScriptFile::SetParameters(asIScriptContext* context, asIScriptFunction* function, const VariantVector& parameters)
  498. {
  499. unsigned paramCount = function->GetParamCount();
  500. for (unsigned i = 0; i < parameters.Size() && i < paramCount; ++i)
  501. {
  502. int paramType = function->GetParamTypeId(i);
  503. switch (paramType)
  504. {
  505. case asTYPEID_BOOL:
  506. context->SetArgByte(i, (unsigned char)parameters[i].GetBool());
  507. break;
  508. case asTYPEID_INT8:
  509. case asTYPEID_UINT8:
  510. context->SetArgByte(i, parameters[i].GetInt());
  511. break;
  512. case asTYPEID_INT16:
  513. case asTYPEID_UINT16:
  514. context->SetArgWord(i, parameters[i].GetInt());
  515. break;
  516. case asTYPEID_INT32:
  517. case asTYPEID_UINT32:
  518. context->SetArgDWord(i, parameters[i].GetInt());
  519. break;
  520. case asTYPEID_FLOAT:
  521. context->SetArgFloat(i, parameters[i].GetFloat());
  522. break;
  523. default:
  524. if (paramType & asTYPEID_APPOBJECT)
  525. {
  526. switch (parameters[i].GetType())
  527. {
  528. case VAR_VECTOR2:
  529. context->SetArgObject(i, (void *)&parameters[i].GetVector2());
  530. break;
  531. case VAR_VECTOR3:
  532. context->SetArgObject(i, (void *)&parameters[i].GetVector3());
  533. break;
  534. case VAR_VECTOR4:
  535. context->SetArgObject(i, (void *)&parameters[i].GetVector4());
  536. break;
  537. case VAR_QUATERNION:
  538. context->SetArgObject(i, (void *)&parameters[i].GetQuaternion());
  539. break;
  540. case VAR_STRING:
  541. context->SetArgObject(i, (void *)&parameters[i].GetString());
  542. break;
  543. case VAR_PTR:
  544. context->SetArgObject(i, (void *)parameters[i].GetPtr());
  545. break;
  546. default:
  547. break;
  548. }
  549. }
  550. break;
  551. }
  552. }
  553. }
  554. void ScriptFile::ReleaseModule()
  555. {
  556. if (scriptModule_)
  557. {
  558. script_->ClearObjectTypeCache();
  559. // Clear search caches and event handlers
  560. includeFiles_.Clear();
  561. validClasses_.Clear();
  562. functions_.Clear();
  563. methods_.Clear();
  564. delayedCalls_.Clear();
  565. UnsubscribeFromAllEventsExcept(PODVector<StringHash>(), true);
  566. // Remove the module
  567. scriptModule_->SetUserData(0);
  568. asIScriptEngine* engine = script_->GetScriptEngine();
  569. engine->DiscardModule(GetName().CString());
  570. scriptModule_ = 0;
  571. compiled_ = false;
  572. SetMemoryUse(0);
  573. ResourceCache* cache = GetSubsystem<ResourceCache>();
  574. if (cache)
  575. cache->ResetDependencies(this);
  576. }
  577. }
  578. void ScriptFile::HandleScriptEvent(StringHash eventType, VariantMap& eventData)
  579. {
  580. if (!compiled_)
  581. return;
  582. ScriptEventData* data = static_cast<ScriptEventData*>(GetEventHandler()->GetUserData());
  583. asIScriptObject* object = data->GetObject();
  584. asIScriptFunction* method = data->GetFunction();
  585. if (object && !data->IsObjectAlive())
  586. {
  587. scriptEventData_.Remove(SharedPtr<ScriptEventData>(data));
  588. UnsubscribeFromEvent(eventType);
  589. return;
  590. }
  591. VariantVector parameters;
  592. if (method->GetParamCount() > 0)
  593. {
  594. parameters.Push(Variant((void*) &eventType));
  595. parameters.Push(Variant((void*) &eventData));
  596. }
  597. if (object)
  598. {
  599. Execute(object, method, parameters);
  600. }
  601. else
  602. {
  603. Execute(method, parameters);
  604. }
  605. }
  606. void ScriptFile::HandleUpdate(StringHash eventType, VariantMap& eventData)
  607. {
  608. if (!compiled_)
  609. return;
  610. using namespace Update;
  611. float timeStep = eventData[P_TIMESTEP].GetFloat();
  612. // Execute delayed calls
  613. for (unsigned i = 0; i < delayedCalls_.Size();)
  614. {
  615. DelayedCall& call = delayedCalls_[i];
  616. bool remove = false;
  617. call.delay_ -= timeStep;
  618. if (call.delay_ <= 0.0f)
  619. {
  620. if (!call.repeat_)
  621. remove = true;
  622. else
  623. call.delay_ += call.period_;
  624. Execute(call.declaration_, call.parameters_);
  625. }
  626. if (remove)
  627. delayedCalls_.Erase(i);
  628. else
  629. ++i;
  630. }
  631. }
  632. ScriptFile* GetScriptContextFile()
  633. {
  634. asIScriptContext* context = asGetActiveContext();
  635. asIScriptFunction* function = context ? context->GetFunction() : 0;
  636. asIScriptModule* module = function ? function->GetEngine()->GetModule(function->GetModuleName()) : 0;
  637. if (module)
  638. return static_cast<ScriptFile*>(module->GetUserData());
  639. else
  640. return 0;
  641. }
  642. }