ScriptFile.cpp 28 KB

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