ScriptFile.cpp 28 KB

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