ScriptFile.cpp 21 KB

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