ScriptFile.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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 "FileSystem.h"
  26. #include "Log.h"
  27. #include "Profiler.h"
  28. #include "ResourceCache.h"
  29. #include "Script.h"
  30. #include "ScriptFile.h"
  31. #include "ScriptInstance.h"
  32. #include <angelscript.h>
  33. #include <cstring>
  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(Deserializer& 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. Deserializer& source_;
  81. };
  82. OBJECTTYPESTATIC(ScriptFile);
  83. ScriptFile::ScriptFile(Context* context) :
  84. Resource(context),
  85. script_(GetSubsystem<Script>()),
  86. scriptModule_(0),
  87. compiled_(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::Load(Deserializer& source)
  99. {
  100. PROFILE(LoadScript);
  101. ReleaseModule();
  102. // Create the module. Discard previous module if there was one
  103. asIScriptEngine* engine = script_->GetScriptEngine();
  104. scriptModule_ = engine->GetModule(GetName().CString(), asGM_ALWAYS_CREATE);
  105. if (!scriptModule_)
  106. {
  107. LOGERROR("Failed to create script module " + GetName());
  108. return false;
  109. }
  110. // Check if this file is precompiled bytecode
  111. if (source.ReadFileID() == "ASBC")
  112. {
  113. ByteCodeDeserializer deserializer = ByteCodeDeserializer(source);
  114. if (scriptModule_->LoadByteCode(&deserializer) >= 0)
  115. {
  116. LOGINFO("Loaded script module " + GetName() + " from bytecode");
  117. compiled_ = true;
  118. // Map script module to script resource with userdata
  119. scriptModule_->SetUserData(this);
  120. return true;
  121. }
  122. else
  123. return false;
  124. }
  125. else
  126. source.Seek(0);
  127. // Not bytecode: add the initial section and check for includes
  128. if (!AddScriptSection(engine, source))
  129. return false;
  130. // Compile. Set script engine logging to retained mode so that potential exceptions can show all error info
  131. ScriptLogMode oldLogMode = script_->GetLogMode();
  132. script_->SetLogMode(LOGMODE_RETAINED);
  133. script_->ClearLogMessages();
  134. int result = scriptModule_->Build();
  135. String errors = script_->GetLogMessages();
  136. script_->SetLogMode(oldLogMode);
  137. if (result < 0)
  138. {
  139. LOGERROR("Failed to compile script module " + GetName() + ":\n" + errors);
  140. return false;
  141. }
  142. if (!errors.Empty())
  143. LOGWARNING(errors);
  144. LOGINFO("Compiled script module " + GetName());
  145. compiled_ = true;
  146. // Map script module to script resource with userdata
  147. scriptModule_->SetUserData(this);
  148. return true;
  149. }
  150. void ScriptFile::AddEventHandler(StringHash eventType, const String& handlerName)
  151. {
  152. if (!compiled_)
  153. return;
  154. String declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  155. asIScriptFunction* function = GetFunction(declaration);
  156. if (!function)
  157. {
  158. declaration = "void " + handlerName + "()";
  159. function = GetFunction(declaration);
  160. if (!function)
  161. {
  162. LOGERROR("Event handler function " + handlerName + " not found in " + GetName());
  163. return;
  164. }
  165. }
  166. SubscribeToEvent(eventType, HANDLER_USERDATA(ScriptFile, HandleScriptEvent, (void*)function));
  167. }
  168. void ScriptFile::AddEventHandler(Object* sender, StringHash eventType, const String& handlerName)
  169. {
  170. if (!compiled_)
  171. return;
  172. if (!sender)
  173. {
  174. LOGERROR("Null event sender for event " + String(eventType) + ", handler " + handlerName);
  175. return;
  176. }
  177. String declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  178. asIScriptFunction* function = GetFunction(declaration);
  179. if (!function)
  180. {
  181. declaration = "void " + handlerName + "()";
  182. function = GetFunction(declaration);
  183. if (!function)
  184. {
  185. LOGERROR("Event handler function " + handlerName + " not found in " + GetName());
  186. return;
  187. }
  188. }
  189. SubscribeToEvent(sender, eventType, HANDLER_USERDATA(ScriptFile, HandleScriptEvent, (void*)function));
  190. }
  191. bool ScriptFile::Execute(const String& declaration, const VariantVector& parameters, bool unprepare)
  192. {
  193. asIScriptFunction* function = GetFunction(declaration);
  194. if (!function)
  195. {
  196. LOGERROR("Function " + declaration + " not found in " + GetName());
  197. return false;
  198. }
  199. return Execute(function, parameters, unprepare);
  200. }
  201. bool ScriptFile::Execute(asIScriptFunction* function, const VariantVector& parameters, bool unprepare)
  202. {
  203. PROFILE(ExecuteFunction);
  204. if (!compiled_ || !function)
  205. return false;
  206. // It is possible that executing the function causes us to unload. Therefore do not rely on member variables
  207. // However, we are not prepared for the whole script system getting destroyed during execution (should never happen)
  208. Script* scriptSystem = script_;
  209. asIScriptContext* context = scriptSystem->GetScriptFileContext();
  210. if (context->Prepare(function) < 0)
  211. return false;
  212. SetParameters(context, function, parameters);
  213. scriptSystem->IncScriptNestingLevel();
  214. bool success = context->Execute() >= 0;
  215. if (unprepare)
  216. context->Unprepare();
  217. scriptSystem->DecScriptNestingLevel();
  218. return success;
  219. }
  220. bool ScriptFile::Execute(asIScriptObject* object, const String& declaration, const VariantVector& parameters, bool unprepare)
  221. {
  222. asIScriptFunction* method = GetMethod(object, declaration);
  223. if (!method)
  224. {
  225. LOGERROR("Method " + declaration + " not found in " + GetName());
  226. return false;
  227. }
  228. return Execute(object, method, parameters, unprepare);
  229. }
  230. bool ScriptFile::Execute(asIScriptObject* object, asIScriptFunction* method, const VariantVector& parameters, bool unprepare)
  231. {
  232. PROFILE(ExecuteMethod);
  233. if (!compiled_ || !object || !method)
  234. return false;
  235. // It is possible that executing the method causes us to unload. Therefore do not rely on member variables
  236. // However, we are not prepared for the whole script system getting destroyed during execution (should never happen)
  237. Script* scriptSystem = script_;
  238. asIScriptContext* context = scriptSystem->GetScriptFileContext();
  239. if (context->Prepare(method) < 0)
  240. return false;
  241. context->SetObject(object);
  242. SetParameters(context, method, parameters);
  243. scriptSystem->IncScriptNestingLevel();
  244. bool success = context->Execute() >= 0;
  245. if (unprepare)
  246. context->Unprepare();
  247. scriptSystem->DecScriptNestingLevel();
  248. return success;
  249. }
  250. asIScriptObject* ScriptFile::CreateObject(const String& className)
  251. {
  252. PROFILE(CreateObject);
  253. if (!compiled_)
  254. return 0;
  255. asIScriptContext* context = script_->GetScriptFileContext();
  256. asIScriptEngine* engine = script_->GetScriptEngine();
  257. asIObjectType *type = engine->GetObjectTypeById(scriptModule_->GetTypeIdByDecl(className.CString()));
  258. if (!type)
  259. return 0;
  260. // Ensure that the type implements the "ScriptObject" interface, so it can be returned to script properly
  261. bool found = false;
  262. HashMap<asIObjectType*, bool>::ConstIterator i = validClasses_.Find(type);
  263. if (i != validClasses_.End())
  264. found = i->second_;
  265. else
  266. {
  267. unsigned numInterfaces = type->GetInterfaceCount();
  268. for (unsigned j = 0; j < numInterfaces; ++j)
  269. {
  270. asIObjectType* interfaceType = type->GetInterface(j);
  271. if (!strcmp(interfaceType->GetName(), "ScriptObject"))
  272. {
  273. found = true;
  274. break;
  275. }
  276. }
  277. validClasses_[type] = found;
  278. }
  279. if (!found)
  280. {
  281. LOGERROR("Script class " + className + " does not implement the ScriptObject interface");
  282. return 0;
  283. }
  284. // Get the factory function id from the object type
  285. String factoryName = className + "@ " + className + "()";
  286. asIScriptFunction* factory = type->GetFactoryByDecl(factoryName.CString());
  287. if (!factory || context->Prepare(factory) < 0 || context->Execute() < 0)
  288. return 0;
  289. asIScriptObject* obj = *(static_cast<asIScriptObject**>(context->GetAddressOfReturnValue()));
  290. if (obj)
  291. obj->AddRef();
  292. return obj;
  293. }
  294. bool ScriptFile::SaveByteCode(Serializer& dest)
  295. {
  296. if (compiled_)
  297. {
  298. dest.WriteFileID("ASBC");
  299. ByteCodeSerializer serializer = ByteCodeSerializer(dest);
  300. return scriptModule_->SaveByteCode(&serializer, true) >= 0;
  301. }
  302. else
  303. return false;
  304. }
  305. asIScriptFunction* ScriptFile::GetFunction(const String& declaration)
  306. {
  307. if (!compiled_)
  308. return 0;
  309. HashMap<String, asIScriptFunction*>::ConstIterator i = functions_.Find(declaration);
  310. if (i != functions_.End())
  311. return i->second_;
  312. asIScriptFunction* function = scriptModule_->GetFunctionByDecl(declaration.CString());
  313. functions_[declaration] = function;
  314. return function;
  315. }
  316. asIScriptFunction* ScriptFile::GetMethod(asIScriptObject* object, const String& declaration)
  317. {
  318. if (!compiled_ || !object)
  319. return 0;
  320. asIObjectType* type = object->GetObjectType();
  321. if (!type)
  322. return 0;
  323. HashMap<asIObjectType*, HashMap<String, asIScriptFunction*> >::ConstIterator i = methods_.Find(type);
  324. if (i != methods_.End())
  325. {
  326. HashMap<String, asIScriptFunction*>::ConstIterator j = i->second_.Find(declaration);
  327. if (j != i->second_.End())
  328. return j->second_;
  329. }
  330. asIScriptFunction* function = type->GetMethodByDecl(declaration.CString());
  331. methods_[type][declaration] = function;
  332. return function;
  333. }
  334. bool ScriptFile::AddScriptSection(asIScriptEngine* engine, Deserializer& source)
  335. {
  336. ResourceCache* cache = GetSubsystem<ResourceCache>();
  337. unsigned dataSize = source.GetSize();
  338. SharedArrayPtr<char> buffer(new char[dataSize]);
  339. source.Read((void*)buffer.Get(), dataSize);
  340. // Pre-parse for includes
  341. // Adapted from Angelscript's scriptbuilder add-on
  342. Vector<String> includeFiles;
  343. unsigned pos = 0;
  344. while(pos < dataSize)
  345. {
  346. int len;
  347. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  348. if (t == asTC_COMMENT || t == asTC_WHITESPACE)
  349. {
  350. pos += len;
  351. continue;
  352. }
  353. // Is this a preprocessor directive?
  354. if (buffer[pos] == '#')
  355. {
  356. int start = pos++;
  357. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  358. if (t == asTC_IDENTIFIER)
  359. {
  360. String token(&buffer[pos], len);
  361. if (token == "include")
  362. {
  363. pos += len;
  364. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  365. if (t == asTC_WHITESPACE)
  366. {
  367. pos += len;
  368. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  369. }
  370. if (t == asTC_VALUE && len > 2 && buffer[pos] == '"')
  371. {
  372. // Get the include file
  373. String includeFile(&buffer[pos+1], len - 2);
  374. pos += len;
  375. // If the file is not found as it is, add the path of current file but only if it is found there
  376. if (!cache->Exists(includeFile))
  377. {
  378. String prefixedIncludeFile = GetPath(GetName()) + includeFile;
  379. if (cache->Exists(prefixedIncludeFile))
  380. includeFile = prefixedIncludeFile;
  381. }
  382. String includeFileLower = includeFile.ToLower();
  383. // If not included yet, store it for later processing
  384. if (!includeFiles_.Contains(includeFileLower))
  385. {
  386. includeFiles_.Insert(includeFileLower);
  387. includeFiles.Push(includeFile);
  388. }
  389. // Overwrite the include directive with space characters to avoid compiler error
  390. memset(&buffer[start], ' ', pos - start);
  391. }
  392. }
  393. }
  394. }
  395. // Don't search includes within statement blocks or between tokens in statements
  396. else
  397. {
  398. int len;
  399. // Skip until ; or { whichever comes first
  400. while (pos < dataSize && buffer[pos] != ';' && buffer[pos] != '{')
  401. {
  402. engine->ParseToken(&buffer[pos], 0, &len);
  403. pos += len;
  404. }
  405. // Skip entire statement block
  406. if (pos < dataSize && buffer[pos] == '{')
  407. {
  408. ++pos;
  409. // Find the end of the statement block
  410. int level = 1;
  411. while (level > 0 && pos < dataSize)
  412. {
  413. asETokenClass t = engine->ParseToken(&buffer[pos], 0, &len);
  414. if (t == asTC_KEYWORD)
  415. {
  416. if (buffer[pos] == '{')
  417. ++level;
  418. else if(buffer[pos] == '}')
  419. --level;
  420. }
  421. pos += len;
  422. }
  423. }
  424. else
  425. ++pos;
  426. }
  427. }
  428. // Process includes first
  429. for (unsigned i = 0; i < includeFiles.Size(); ++i)
  430. {
  431. cache->StoreResourceDependency(this, includeFiles[i]);
  432. SharedPtr<File> file = cache->GetFile(includeFiles[i]);
  433. if (file)
  434. {
  435. if (!AddScriptSection(engine, *file))
  436. return false;
  437. }
  438. else
  439. {
  440. LOGERROR("Could not process all the include directives in " + GetName() + ": missing " + includeFiles[i]);
  441. return false;
  442. }
  443. }
  444. // Then add this section
  445. if (scriptModule_->AddScriptSection(source.GetName().CString(), (const char*)buffer.Get(), dataSize) < 0)
  446. {
  447. LOGERROR("Failed to add script section " + source.GetName());
  448. return false;
  449. }
  450. SetMemoryUse(GetMemoryUse() + dataSize);
  451. return true;
  452. }
  453. void ScriptFile::SetParameters(asIScriptContext* context, asIScriptFunction* function, const VariantVector& parameters)
  454. {
  455. unsigned paramCount = function->GetParamCount();
  456. for (unsigned i = 0; i < parameters.Size() && i < paramCount; ++i)
  457. {
  458. int paramType = function->GetParamTypeId(i);
  459. switch (paramType)
  460. {
  461. case asTYPEID_BOOL:
  462. context->SetArgByte(i, (unsigned char)parameters[i].GetBool());
  463. break;
  464. case asTYPEID_INT8:
  465. case asTYPEID_UINT8:
  466. context->SetArgByte(i, parameters[i].GetInt());
  467. break;
  468. case asTYPEID_INT16:
  469. case asTYPEID_UINT16:
  470. context->SetArgWord(i, parameters[i].GetInt());
  471. break;
  472. case asTYPEID_INT32:
  473. case asTYPEID_UINT32:
  474. context->SetArgDWord(i, parameters[i].GetInt());
  475. break;
  476. case asTYPEID_FLOAT:
  477. context->SetArgFloat(i, parameters[i].GetFloat());
  478. break;
  479. default:
  480. if (paramType & asTYPEID_APPOBJECT)
  481. {
  482. switch (parameters[i].GetType())
  483. {
  484. case VAR_VECTOR2:
  485. context->SetArgObject(i, (void *)&parameters[i].GetVector2());
  486. break;
  487. case VAR_VECTOR3:
  488. context->SetArgObject(i, (void *)&parameters[i].GetVector3());
  489. break;
  490. case VAR_VECTOR4:
  491. context->SetArgObject(i, (void *)&parameters[i].GetVector4());
  492. break;
  493. case VAR_QUATERNION:
  494. context->SetArgObject(i, (void *)&parameters[i].GetQuaternion());
  495. break;
  496. case VAR_STRING:
  497. context->SetArgObject(i, (void *)&parameters[i].GetString());
  498. break;
  499. case VAR_PTR:
  500. context->SetArgObject(i, (void *)parameters[i].GetPtr());
  501. break;
  502. default:
  503. break;
  504. }
  505. }
  506. break;
  507. }
  508. }
  509. }
  510. void ScriptFile::ReleaseModule()
  511. {
  512. if (scriptModule_)
  513. {
  514. script_->ClearObjectTypeCache();
  515. // Clear search caches and event handlers
  516. includeFiles_.Clear();
  517. validClasses_.Clear();
  518. functions_.Clear();
  519. methods_.Clear();
  520. UnsubscribeFromAllEventsExcept(PODVector<StringHash>(), true);
  521. // Remove the module
  522. scriptModule_->SetUserData(0);
  523. asIScriptEngine* engine = script_->GetScriptEngine();
  524. engine->DiscardModule(GetName().CString());
  525. scriptModule_ = 0;
  526. compiled_ = false;
  527. SetMemoryUse(0);
  528. ResourceCache* cache = GetSubsystem<ResourceCache>();
  529. if (cache)
  530. cache->ResetDependencies(this);
  531. }
  532. }
  533. void ScriptFile::HandleScriptEvent(StringHash eventType, VariantMap& eventData)
  534. {
  535. if (!compiled_)
  536. return;
  537. asIScriptFunction* function = static_cast<asIScriptFunction*>(GetEventHandler()->GetUserData());
  538. VariantVector parameters;
  539. if (function->GetParamCount() > 0)
  540. {
  541. parameters.Push(Variant((void*)&eventType));
  542. parameters.Push(Variant((void*)&eventData));
  543. }
  544. Execute(function, parameters);
  545. }
  546. ScriptFile* GetScriptContextFile()
  547. {
  548. asIScriptContext* context = asGetActiveContext();
  549. asIScriptFunction* function = context ? context->GetFunction() : 0;
  550. asIScriptModule* module = function ? function->GetEngine()->GetModule(function->GetModuleName()) : 0;
  551. if (module)
  552. return static_cast<ScriptFile*>(module->GetUserData());
  553. else
  554. return 0;
  555. }
  556. }