ScriptFile.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. //
  2. // Copyright (c) 2008-2014 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 "CoreEvents.h"
  25. #include "FileSystem.h"
  26. #include "Log.h"
  27. #include "MemoryBuffer.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(MemoryBuffer& 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. MemoryBuffer& 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::BeginLoad(Deserializer& source)
  100. {
  101. ReleaseModule();
  102. loadByteCode_.Reset();
  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. // Perform actual parsing in EndLoad(); read data now
  115. loadByteCodeSize_ = source.GetSize() - source.GetPosition();
  116. loadByteCode_ = new unsigned char[loadByteCodeSize_];
  117. source.Read(loadByteCode_.Get(), loadByteCodeSize_);
  118. return true;
  119. }
  120. else
  121. source.Seek(0);
  122. // Not bytecode: add the initial section and check for includes.
  123. // Perform actual building during EndLoad(), as AngelScript can not multithread module compilation,
  124. // and static initializers may access arbitrary engine functionality which may not be thread-safe
  125. return AddScriptSection(engine, source);
  126. }
  127. bool ScriptFile::EndLoad()
  128. {
  129. bool success = false;
  130. // Load from bytecode if available, else compile
  131. if (loadByteCode_)
  132. {
  133. MemoryBuffer buffer(loadByteCode_.Get(), loadByteCodeSize_);
  134. ByteCodeDeserializer deserializer = ByteCodeDeserializer(buffer);
  135. if (scriptModule_->LoadByteCode(&deserializer) >= 0)
  136. {
  137. LOGINFO("Loaded script module " + GetName() + " from bytecode");
  138. success = true;
  139. }
  140. }
  141. else
  142. {
  143. int result = scriptModule_->Build();
  144. if (result >= 0)
  145. {
  146. LOGINFO("Compiled script module " + GetName());
  147. success = true;
  148. }
  149. else
  150. LOGERROR("Failed to compile script module " + GetName());
  151. }
  152. if (success)
  153. {
  154. compiled_ = true;
  155. // Map script module to script resource with userdata
  156. scriptModule_->SetUserData(this);
  157. }
  158. loadByteCode_.Reset();
  159. return success;
  160. }
  161. void ScriptFile::AddEventHandler(StringHash eventType, const String& handlerName)
  162. {
  163. if (!compiled_)
  164. return;
  165. AddEventHandlerInternal(0, eventType, handlerName);
  166. }
  167. void ScriptFile::AddEventHandler(Object* sender, StringHash eventType, const String& handlerName)
  168. {
  169. if (!compiled_)
  170. return;
  171. if (!sender)
  172. {
  173. LOGERROR("Null event sender for event " + String(eventType) + ", handler " + handlerName);
  174. return;
  175. }
  176. AddEventHandlerInternal(sender, eventType, handlerName);
  177. }
  178. void ScriptFile::RemoveEventHandler(StringHash eventType)
  179. {
  180. asIScriptObject* receiver = static_cast<asIScriptObject*>(asGetActiveContext()->GetThisPointer());
  181. HashMap<asIScriptObject*, SharedPtr<ScriptEventInvoker> >::Iterator i = eventInvokers_.Find(receiver);
  182. if (i != eventInvokers_.End())
  183. {
  184. i->second_->UnsubscribeFromEvent(eventType);
  185. // If no longer have any subscribed events, remove the event invoker object
  186. if (!i->second_->HasEventHandlers())
  187. eventInvokers_.Erase(i);
  188. }
  189. }
  190. void ScriptFile::RemoveEventHandler(Object* sender, StringHash eventType)
  191. {
  192. asIScriptObject* receiver = static_cast<asIScriptObject*>(asGetActiveContext()->GetThisPointer());
  193. HashMap<asIScriptObject*, SharedPtr<ScriptEventInvoker> >::Iterator i = eventInvokers_.Find(receiver);
  194. if (i != eventInvokers_.End())
  195. {
  196. i->second_->UnsubscribeFromEvent(sender, eventType);
  197. if (!i->second_->HasEventHandlers())
  198. eventInvokers_.Erase(i);
  199. }
  200. }
  201. void ScriptFile::RemoveEventHandlers(Object* sender)
  202. {
  203. asIScriptObject* receiver = static_cast<asIScriptObject*>(asGetActiveContext()->GetThisPointer());
  204. HashMap<asIScriptObject*, SharedPtr<ScriptEventInvoker> >::Iterator i = eventInvokers_.Find(receiver);
  205. if (i != eventInvokers_.End())
  206. {
  207. i->second_->UnsubscribeFromEvents(sender);
  208. if (!i->second_->HasEventHandlers())
  209. eventInvokers_.Erase(i);
  210. }
  211. }
  212. void ScriptFile::RemoveEventHandlers()
  213. {
  214. asIScriptObject* receiver = static_cast<asIScriptObject*>(asGetActiveContext()->GetThisPointer());
  215. HashMap<asIScriptObject*, SharedPtr<ScriptEventInvoker> >::Iterator i = eventInvokers_.Find(receiver);
  216. if (i != eventInvokers_.End())
  217. {
  218. i->second_->UnsubscribeFromAllEvents();
  219. if (!i->second_->HasEventHandlers())
  220. eventInvokers_.Erase(i);
  221. }
  222. }
  223. void ScriptFile::RemoveEventHandlersExcept(const PODVector<StringHash>& exceptions)
  224. {
  225. asIScriptObject* receiver = static_cast<asIScriptObject*>(asGetActiveContext()->GetThisPointer());
  226. HashMap<asIScriptObject*, SharedPtr<ScriptEventInvoker> >::Iterator i = eventInvokers_.Find(receiver);
  227. if (i != eventInvokers_.End())
  228. {
  229. i->second_->UnsubscribeFromAllEventsExcept(exceptions, true);
  230. if (!i->second_->HasEventHandlers())
  231. eventInvokers_.Erase(i);
  232. }
  233. }
  234. bool ScriptFile::Execute(const String& declaration, const VariantVector& parameters, bool unprepare)
  235. {
  236. asIScriptFunction* function = GetFunction(declaration);
  237. if (!function)
  238. {
  239. LOGERROR("Function " + declaration + " not found in " + GetName());
  240. return false;
  241. }
  242. return Execute(function, parameters, unprepare);
  243. }
  244. bool ScriptFile::Execute(asIScriptFunction* function, const VariantVector& parameters, bool unprepare)
  245. {
  246. PROFILE(ExecuteFunction);
  247. if (!compiled_ || !function)
  248. return false;
  249. // It is possible that executing the function 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(function) < 0)
  254. return false;
  255. SetParameters(context, function, parameters);
  256. scriptSystem->IncScriptNestingLevel();
  257. bool success = context->Execute() >= 0;
  258. if (unprepare)
  259. context->Unprepare();
  260. scriptSystem->DecScriptNestingLevel();
  261. return success;
  262. }
  263. bool ScriptFile::Execute(asIScriptObject* object, const String& declaration, const VariantVector& parameters, bool unprepare)
  264. {
  265. asIScriptFunction* method = GetMethod(object, declaration);
  266. if (!method)
  267. {
  268. LOGERROR("Method " + declaration + " not found in " + GetName());
  269. return false;
  270. }
  271. return Execute(object, method, parameters, unprepare);
  272. }
  273. bool ScriptFile::Execute(asIScriptObject* object, asIScriptFunction* method, const VariantVector& parameters, bool unprepare)
  274. {
  275. PROFILE(ExecuteMethod);
  276. if (!compiled_ || !object || !method)
  277. return false;
  278. // It is possible that executing the method causes us to unload. Therefore do not rely on member variables
  279. // However, we are not prepared for the whole script system getting destroyed during execution (should never happen)
  280. Script* scriptSystem = script_;
  281. asIScriptContext* context = scriptSystem->GetScriptFileContext();
  282. if (context->Prepare(method) < 0)
  283. return false;
  284. context->SetObject(object);
  285. SetParameters(context, method, parameters);
  286. scriptSystem->IncScriptNestingLevel();
  287. bool success = context->Execute() >= 0;
  288. if (unprepare)
  289. context->Unprepare();
  290. scriptSystem->DecScriptNestingLevel();
  291. return success;
  292. }
  293. void ScriptFile::DelayedExecute(float delay, bool repeat, const String& declaration, const VariantVector& parameters)
  294. {
  295. DelayedCall call;
  296. call.period_ = call.delay_ = Max(delay, 0.0f);
  297. call.repeat_ = repeat;
  298. call.declaration_ = declaration;
  299. call.parameters_ = parameters;
  300. delayedCalls_.Push(call);
  301. // Make sure we are registered to the application update event, because delayed calls are executed there
  302. if (!subscribed_)
  303. {
  304. SubscribeToEvent(E_UPDATE, HANDLER(ScriptFile, HandleUpdate));
  305. subscribed_ = true;
  306. }
  307. }
  308. void ScriptFile::ClearDelayedExecute(const String& declaration)
  309. {
  310. if (declaration.Empty())
  311. delayedCalls_.Clear();
  312. else
  313. {
  314. for (Vector<DelayedCall>::Iterator i = delayedCalls_.Begin(); i != delayedCalls_.End();)
  315. {
  316. if (declaration == i->declaration_)
  317. i = delayedCalls_.Erase(i);
  318. else
  319. ++i;
  320. }
  321. }
  322. }
  323. asIScriptObject* ScriptFile::CreateObject(const String& className)
  324. {
  325. PROFILE(CreateObject);
  326. if (!compiled_)
  327. return 0;
  328. asIScriptContext* context = script_->GetScriptFileContext();
  329. asIScriptEngine* engine = script_->GetScriptEngine();
  330. asIObjectType *type = engine->GetObjectTypeById(scriptModule_->GetTypeIdByDecl(className.CString()));
  331. if (!type)
  332. return 0;
  333. // Ensure that the type implements the "ScriptObject" interface, so it can be returned to script properly
  334. bool found = false;
  335. HashMap<asIObjectType*, bool>::ConstIterator i = validClasses_.Find(type);
  336. if (i != validClasses_.End())
  337. found = i->second_;
  338. else
  339. {
  340. unsigned numInterfaces = type->GetInterfaceCount();
  341. for (unsigned j = 0; j < numInterfaces; ++j)
  342. {
  343. asIObjectType* interfaceType = type->GetInterface(j);
  344. if (!strcmp(interfaceType->GetName(), "ScriptObject"))
  345. {
  346. found = true;
  347. break;
  348. }
  349. }
  350. validClasses_[type] = found;
  351. }
  352. if (!found)
  353. {
  354. LOGERROR("Script class " + className + " does not implement the ScriptObject interface");
  355. return 0;
  356. }
  357. // Get the factory function id from the object type
  358. String factoryName = className + "@ " + className + "()";
  359. asIScriptFunction* factory = type->GetFactoryByDecl(factoryName.CString());
  360. if (!factory || context->Prepare(factory) < 0 || context->Execute() < 0)
  361. return 0;
  362. asIScriptObject* obj = *(static_cast<asIScriptObject**>(context->GetAddressOfReturnValue()));
  363. if (obj)
  364. obj->AddRef();
  365. return obj;
  366. }
  367. bool ScriptFile::SaveByteCode(Serializer& dest)
  368. {
  369. if (compiled_)
  370. {
  371. dest.WriteFileID("ASBC");
  372. ByteCodeSerializer serializer = ByteCodeSerializer(dest);
  373. return scriptModule_->SaveByteCode(&serializer, true) >= 0;
  374. }
  375. else
  376. return false;
  377. }
  378. asIScriptFunction* ScriptFile::GetFunction(const String& declaration)
  379. {
  380. if (!compiled_)
  381. return 0;
  382. HashMap<String, asIScriptFunction*>::ConstIterator i = functions_.Find(declaration);
  383. if (i != functions_.End())
  384. return i->second_;
  385. asIScriptFunction* function = scriptModule_->GetFunctionByDecl(declaration.CString());
  386. functions_[declaration] = function;
  387. return function;
  388. }
  389. asIScriptFunction* ScriptFile::GetMethod(asIScriptObject* object, const String& declaration)
  390. {
  391. if (!compiled_ || !object)
  392. return 0;
  393. asIObjectType* type = object->GetObjectType();
  394. if (!type)
  395. return 0;
  396. HashMap<asIObjectType*, HashMap<String, asIScriptFunction*> >::ConstIterator i = methods_.Find(type);
  397. if (i != methods_.End())
  398. {
  399. HashMap<String, asIScriptFunction*>::ConstIterator j = i->second_.Find(declaration);
  400. if (j != i->second_.End())
  401. return j->second_;
  402. }
  403. asIScriptFunction* function = type->GetMethodByDecl(declaration.CString());
  404. methods_[type][declaration] = function;
  405. return function;
  406. }
  407. void ScriptFile::CleanupEventInvoker(asIScriptObject* object)
  408. {
  409. eventInvokers_.Erase(object);
  410. }
  411. void ScriptFile::AddEventHandlerInternal(Object* sender, StringHash eventType, const String& handlerName)
  412. {
  413. String declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  414. asIScriptFunction* function = 0;
  415. asIScriptObject* receiver = static_cast<asIScriptObject*>(asGetActiveContext()->GetThisPointer());
  416. if (receiver)
  417. function = GetMethod(receiver, declaration);
  418. else
  419. function = GetFunction(declaration);
  420. if (!function)
  421. {
  422. declaration = "void " + handlerName + "()";
  423. if (receiver)
  424. function = GetMethod(receiver, declaration);
  425. else
  426. function = GetFunction(declaration);
  427. if (!function)
  428. {
  429. LOGERROR("Event handler function " + handlerName + " not found in " + GetName());
  430. return;
  431. }
  432. }
  433. HashMap<asIScriptObject*, SharedPtr<ScriptEventInvoker> >::Iterator i = eventInvokers_.Find(receiver);
  434. // Remove previous handler in case an object pointer gets reused
  435. if (i != eventInvokers_.End() && !i->second_->IsObjectAlive())
  436. {
  437. eventInvokers_.Erase(i);
  438. i = eventInvokers_.End();
  439. }
  440. if (i == eventInvokers_.End())
  441. i = eventInvokers_.Insert(MakePair(receiver, SharedPtr<ScriptEventInvoker>(new ScriptEventInvoker(this, receiver))));
  442. if (!sender)
  443. {
  444. i->second_->SubscribeToEvent(eventType, new EventHandlerImpl<ScriptEventInvoker>
  445. (i->second_, &ScriptEventInvoker::HandleScriptEvent, (void*)function));
  446. }
  447. else
  448. {
  449. i->second_->SubscribeToEvent(sender, eventType, new EventHandlerImpl<ScriptEventInvoker>
  450. (i->second_, &ScriptEventInvoker::HandleScriptEvent, (void*)function));
  451. }
  452. }
  453. bool ScriptFile::AddScriptSection(asIScriptEngine* engine, Deserializer& source)
  454. {
  455. ResourceCache* cache = GetSubsystem<ResourceCache>();
  456. unsigned dataSize = source.GetSize();
  457. SharedArrayPtr<char> buffer(new char[dataSize]);
  458. source.Read((void*)buffer.Get(), dataSize);
  459. // Pre-parse for includes
  460. // Adapted from Angelscript's scriptbuilder add-on
  461. Vector<String> includeFiles;
  462. unsigned pos = 0;
  463. while(pos < dataSize)
  464. {
  465. int len;
  466. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  467. if (t == asTC_COMMENT || t == asTC_WHITESPACE)
  468. {
  469. pos += len;
  470. continue;
  471. }
  472. // Is this a preprocessor directive?
  473. if (buffer[pos] == '#')
  474. {
  475. int start = pos++;
  476. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  477. if (t == asTC_IDENTIFIER)
  478. {
  479. String token(&buffer[pos], len);
  480. if (token == "include")
  481. {
  482. pos += len;
  483. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  484. if (t == asTC_WHITESPACE)
  485. {
  486. pos += len;
  487. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  488. }
  489. if (t == asTC_VALUE && len > 2 && buffer[pos] == '"')
  490. {
  491. // Get the include file
  492. String includeFile(&buffer[pos+1], len - 2);
  493. pos += len;
  494. // If the file is not found as it is, add the path of current file but only if it is found there
  495. if (!cache->Exists(includeFile))
  496. {
  497. String prefixedIncludeFile = GetPath(GetName()) + includeFile;
  498. if (cache->Exists(prefixedIncludeFile))
  499. includeFile = prefixedIncludeFile;
  500. }
  501. String includeFileLower = includeFile.ToLower();
  502. // If not included yet, store it for later processing
  503. if (!includeFiles_.Contains(includeFileLower))
  504. {
  505. includeFiles_.Insert(includeFileLower);
  506. includeFiles.Push(includeFile);
  507. }
  508. // Overwrite the include directive with space characters to avoid compiler error
  509. memset(&buffer[start], ' ', pos - start);
  510. }
  511. }
  512. }
  513. }
  514. // Don't search includes within statement blocks or between tokens in statements
  515. else
  516. {
  517. int len;
  518. // Skip until ; or { whichever comes first
  519. while (pos < dataSize && buffer[pos] != ';' && buffer[pos] != '{')
  520. {
  521. engine->ParseToken(&buffer[pos], 0, &len);
  522. pos += len;
  523. }
  524. // Skip entire statement block
  525. if (pos < dataSize && buffer[pos] == '{')
  526. {
  527. ++pos;
  528. // Find the end of the statement block
  529. int level = 1;
  530. while (level > 0 && pos < dataSize)
  531. {
  532. asETokenClass t = engine->ParseToken(&buffer[pos], 0, &len);
  533. if (t == asTC_KEYWORD)
  534. {
  535. if (buffer[pos] == '{')
  536. ++level;
  537. else if(buffer[pos] == '}')
  538. --level;
  539. }
  540. pos += len;
  541. }
  542. }
  543. else
  544. ++pos;
  545. }
  546. }
  547. // Process includes first
  548. for (unsigned i = 0; i < includeFiles.Size(); ++i)
  549. {
  550. cache->StoreResourceDependency(this, includeFiles[i]);
  551. SharedPtr<File> file = cache->GetFile(includeFiles[i]);
  552. if (file)
  553. {
  554. if (!AddScriptSection(engine, *file))
  555. return false;
  556. }
  557. else
  558. {
  559. LOGERROR("Could not process all the include directives in " + GetName() + ": missing " + includeFiles[i]);
  560. return false;
  561. }
  562. }
  563. // Then add this section
  564. if (scriptModule_->AddScriptSection(source.GetName().CString(), (const char*)buffer.Get(), dataSize) < 0)
  565. {
  566. LOGERROR("Failed to add script section " + source.GetName());
  567. return false;
  568. }
  569. SetMemoryUse(GetMemoryUse() + dataSize);
  570. return true;
  571. }
  572. void ScriptFile::SetParameters(asIScriptContext* context, asIScriptFunction* function, const VariantVector& parameters)
  573. {
  574. unsigned paramCount = function->GetParamCount();
  575. for (unsigned i = 0; i < parameters.Size() && i < paramCount; ++i)
  576. {
  577. int paramTypeId;
  578. function->GetParam(i, &paramTypeId);
  579. switch (paramTypeId)
  580. {
  581. case asTYPEID_BOOL:
  582. context->SetArgByte(i, (unsigned char)parameters[i].GetBool());
  583. break;
  584. case asTYPEID_INT8:
  585. case asTYPEID_UINT8:
  586. context->SetArgByte(i, parameters[i].GetInt());
  587. break;
  588. case asTYPEID_INT16:
  589. case asTYPEID_UINT16:
  590. context->SetArgWord(i, parameters[i].GetInt());
  591. break;
  592. case asTYPEID_INT32:
  593. case asTYPEID_UINT32:
  594. context->SetArgDWord(i, parameters[i].GetInt());
  595. break;
  596. case asTYPEID_FLOAT:
  597. context->SetArgFloat(i, parameters[i].GetFloat());
  598. break;
  599. default:
  600. if (paramTypeId & asTYPEID_APPOBJECT)
  601. {
  602. switch (parameters[i].GetType())
  603. {
  604. case VAR_VECTOR2:
  605. context->SetArgObject(i, (void*)&parameters[i].GetVector2());
  606. break;
  607. case VAR_VECTOR3:
  608. context->SetArgObject(i, (void*)&parameters[i].GetVector3());
  609. break;
  610. case VAR_VECTOR4:
  611. context->SetArgObject(i, (void*)&parameters[i].GetVector4());
  612. break;
  613. case VAR_QUATERNION:
  614. context->SetArgObject(i, (void*)&parameters[i].GetQuaternion());
  615. break;
  616. case VAR_STRING:
  617. context->SetArgObject(i, (void*)&parameters[i].GetString());
  618. break;
  619. case VAR_VOIDPTR:
  620. context->SetArgObject(i, parameters[i].GetVoidPtr());
  621. break;
  622. case VAR_PTR:
  623. context->SetArgObject(i, (void*)parameters[i].GetPtr());
  624. break;
  625. default:
  626. break;
  627. }
  628. }
  629. break;
  630. }
  631. }
  632. }
  633. void ScriptFile::ReleaseModule()
  634. {
  635. if (scriptModule_)
  636. {
  637. script_->ClearObjectTypeCache();
  638. // Clear search caches and event handlers
  639. includeFiles_.Clear();
  640. validClasses_.Clear();
  641. functions_.Clear();
  642. methods_.Clear();
  643. delayedCalls_.Clear();
  644. eventInvokers_.Clear();
  645. // Remove the module
  646. scriptModule_->SetUserData(0);
  647. asIScriptEngine* engine = script_->GetScriptEngine();
  648. engine->DiscardModule(GetName().CString());
  649. scriptModule_ = 0;
  650. compiled_ = false;
  651. SetMemoryUse(0);
  652. ResourceCache* cache = GetSubsystem<ResourceCache>();
  653. cache->ResetDependencies(this);
  654. }
  655. }
  656. void ScriptFile::HandleUpdate(StringHash eventType, VariantMap& eventData)
  657. {
  658. if (!compiled_)
  659. return;
  660. using namespace Update;
  661. float timeStep = eventData[P_TIMESTEP].GetFloat();
  662. // Execute delayed calls
  663. for (unsigned i = 0; i < delayedCalls_.Size();)
  664. {
  665. DelayedCall& call = delayedCalls_[i];
  666. bool remove = false;
  667. call.delay_ -= timeStep;
  668. if (call.delay_ <= 0.0f)
  669. {
  670. if (!call.repeat_)
  671. remove = true;
  672. else
  673. call.delay_ += call.period_;
  674. Execute(call.declaration_, call.parameters_);
  675. }
  676. if (remove)
  677. delayedCalls_.Erase(i);
  678. else
  679. ++i;
  680. }
  681. }
  682. ScriptEventInvoker::ScriptEventInvoker(ScriptFile* file, asIScriptObject* object) :
  683. Object(file->GetContext()),
  684. file_(file),
  685. sharedBool_(0),
  686. object_(object)
  687. {
  688. if (object_)
  689. {
  690. sharedBool_ = object_->GetEngine()->GetWeakRefFlagOfScriptObject(object_, object_->GetObjectType());
  691. if (sharedBool_)
  692. sharedBool_->AddRef();
  693. }
  694. }
  695. ScriptEventInvoker::~ScriptEventInvoker()
  696. {
  697. if (sharedBool_)
  698. sharedBool_->Release();
  699. sharedBool_ = 0;
  700. object_ = 0;
  701. }
  702. bool ScriptEventInvoker::IsObjectAlive() const
  703. {
  704. if (sharedBool_)
  705. {
  706. // Return inverse as Get returns true when an asIScriptObject is dead.
  707. return !sharedBool_->Get();
  708. }
  709. return true;
  710. }
  711. void ScriptEventInvoker::HandleScriptEvent(StringHash eventType, VariantMap& eventData)
  712. {
  713. if (!file_->IsCompiled())
  714. return;
  715. asIScriptFunction* method = static_cast<asIScriptFunction*>(GetEventHandler()->GetUserData());
  716. if (object_ && !IsObjectAlive())
  717. {
  718. file_->CleanupEventInvoker(object_);
  719. return;
  720. }
  721. VariantVector parameters;
  722. if (method->GetParamCount() > 0)
  723. {
  724. parameters.Push(Variant((void*)&eventType));
  725. parameters.Push(Variant((void*)&eventData));
  726. }
  727. if (object_)
  728. file_->Execute(object_, method, parameters);
  729. else
  730. file_->Execute(method, parameters);
  731. }
  732. ScriptFile* GetScriptContextFile()
  733. {
  734. asIScriptContext* context = asGetActiveContext();
  735. asIScriptFunction* function = context ? context->GetFunction() : 0;
  736. asIScriptModule* module = function ? function->GetEngine()->GetModule(function->GetModuleName()) : 0;
  737. if (module)
  738. return static_cast<ScriptFile*>(module->GetUserData());
  739. else
  740. return 0;
  741. }
  742. }