ScriptFile.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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. GetSubsystem<ResourceCache>()->ResetDependencies(this);
  103. // Create the module. Discard previous module if there was one
  104. asIScriptEngine* engine = script_->GetScriptEngine();
  105. scriptModule_ = engine->GetModule(GetName().CString(), asGM_ALWAYS_CREATE);
  106. if (!scriptModule_)
  107. {
  108. LOGERROR("Failed to create script module " + GetName());
  109. return false;
  110. }
  111. // Check if this file is precompiled bytecode
  112. if (source.ReadFileID() == "ASBC")
  113. {
  114. if (scriptModule_->LoadByteCode(&ByteCodeDeserializer(source)) >= 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. return scriptModule_->SaveByteCode(&ByteCodeSerializer(dest), true) >= 0;
  300. }
  301. else
  302. return false;
  303. }
  304. asIScriptFunction* ScriptFile::GetFunction(const String& declaration)
  305. {
  306. if (!compiled_)
  307. return 0;
  308. HashMap<String, asIScriptFunction*>::ConstIterator i = functions_.Find(declaration);
  309. if (i != functions_.End())
  310. return i->second_;
  311. asIScriptFunction* function = scriptModule_->GetFunctionByDecl(declaration.CString());
  312. functions_[declaration] = function;
  313. return function;
  314. }
  315. asIScriptFunction* ScriptFile::GetMethod(asIScriptObject* object, const String& declaration)
  316. {
  317. if (!compiled_ || !object)
  318. return 0;
  319. asIObjectType* type = object->GetObjectType();
  320. if (!type)
  321. return 0;
  322. HashMap<asIObjectType*, HashMap<String, asIScriptFunction*> >::ConstIterator i = methods_.Find(type);
  323. if (i != methods_.End())
  324. {
  325. HashMap<String, asIScriptFunction*>::ConstIterator j = i->second_.Find(declaration);
  326. if (j != i->second_.End())
  327. return j->second_;
  328. }
  329. asIScriptFunction* function = type->GetMethodByDecl(declaration.CString());
  330. methods_[type][declaration] = function;
  331. return function;
  332. }
  333. bool ScriptFile::AddScriptSection(asIScriptEngine* engine, Deserializer& source)
  334. {
  335. ResourceCache* cache = GetSubsystem<ResourceCache>();
  336. unsigned dataSize = source.GetSize();
  337. SharedArrayPtr<char> buffer(new char[dataSize]);
  338. source.Read((void*)buffer.Get(), dataSize);
  339. // Pre-parse for includes
  340. // Adapted from Angelscript's scriptbuilder add-on
  341. Vector<String> includeFiles;
  342. unsigned pos = 0;
  343. while(pos < dataSize)
  344. {
  345. int len;
  346. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  347. if (t == asTC_COMMENT || t == asTC_WHITESPACE)
  348. {
  349. pos += len;
  350. continue;
  351. }
  352. // Is this a preprocessor directive?
  353. if (buffer[pos] == '#')
  354. {
  355. int start = pos++;
  356. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  357. if (t == asTC_IDENTIFIER)
  358. {
  359. String token(&buffer[pos], len);
  360. if (token == "include")
  361. {
  362. pos += len;
  363. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  364. if (t == asTC_WHITESPACE)
  365. {
  366. pos += len;
  367. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  368. }
  369. if (t == asTC_VALUE && len > 2 && buffer[pos] == '"')
  370. {
  371. // Get the include file
  372. String includeFile(&buffer[pos+1], len - 2);
  373. pos += len;
  374. // If the file is not found as it is, add the path of current file but only if it is found there
  375. if (!cache->Exists(includeFile))
  376. {
  377. String prefixedIncludeFile = GetPath(GetName()) + includeFile;
  378. if (cache->Exists(prefixedIncludeFile))
  379. includeFile = prefixedIncludeFile;
  380. }
  381. String includeFileLower = includeFile.ToLower();
  382. // If not included yet, store it for later processing
  383. if (!includeFiles_.Contains(includeFileLower))
  384. {
  385. includeFiles_.Insert(includeFileLower);
  386. includeFiles.Push(includeFile);
  387. }
  388. // Overwrite the include directive with space characters to avoid compiler error
  389. memset(&buffer[start], ' ', pos - start);
  390. }
  391. }
  392. }
  393. }
  394. // Don't search includes within statement blocks or between tokens in statements
  395. else
  396. {
  397. int len;
  398. // Skip until ; or { whichever comes first
  399. while (pos < dataSize && buffer[pos] != ';' && buffer[pos] != '{')
  400. {
  401. engine->ParseToken(&buffer[pos], 0, &len);
  402. pos += len;
  403. }
  404. // Skip entire statement block
  405. if (pos < dataSize && buffer[pos] == '{')
  406. {
  407. ++pos;
  408. // Find the end of the statement block
  409. int level = 1;
  410. while (level > 0 && pos < dataSize)
  411. {
  412. asETokenClass t = engine->ParseToken(&buffer[pos], 0, &len);
  413. if (t == asTC_KEYWORD)
  414. {
  415. if (buffer[pos] == '{')
  416. ++level;
  417. else if(buffer[pos] == '}')
  418. --level;
  419. }
  420. pos += len;
  421. }
  422. }
  423. else
  424. ++pos;
  425. }
  426. }
  427. // Process includes first
  428. for (unsigned i = 0; i < includeFiles.Size(); ++i)
  429. {
  430. cache->StoreResourceDependency(this, includeFiles[i]);
  431. SharedPtr<File> file = cache->GetFile(includeFiles[i]);
  432. if (file)
  433. {
  434. if (!AddScriptSection(engine, *file))
  435. return false;
  436. }
  437. else
  438. {
  439. LOGERROR("Could not process all the include directives in " + GetName());
  440. return false;
  441. }
  442. }
  443. // Then add this section
  444. if (scriptModule_->AddScriptSection(source.GetName().CString(), (const char*)buffer.Get(), dataSize) < 0)
  445. {
  446. LOGERROR("Failed to add script section " + source.GetName());
  447. return false;
  448. }
  449. SetMemoryUse(GetMemoryUse() + dataSize);
  450. return true;
  451. }
  452. void ScriptFile::SetParameters(asIScriptContext* context, asIScriptFunction* function, const VariantVector& parameters)
  453. {
  454. unsigned paramCount = function->GetParamCount();
  455. for (unsigned i = 0; i < parameters.Size() && i < paramCount; ++i)
  456. {
  457. int paramType = function->GetParamTypeId(i);
  458. switch (paramType)
  459. {
  460. case asTYPEID_BOOL:
  461. context->SetArgByte(i, (unsigned char)parameters[i].GetBool());
  462. break;
  463. case asTYPEID_INT8:
  464. case asTYPEID_UINT8:
  465. context->SetArgByte(i, parameters[i].GetInt());
  466. break;
  467. case asTYPEID_INT16:
  468. case asTYPEID_UINT16:
  469. context->SetArgWord(i, parameters[i].GetInt());
  470. break;
  471. case asTYPEID_INT32:
  472. case asTYPEID_UINT32:
  473. context->SetArgDWord(i, parameters[i].GetInt());
  474. break;
  475. case asTYPEID_FLOAT:
  476. context->SetArgFloat(i, parameters[i].GetFloat());
  477. break;
  478. default:
  479. if (paramType & asTYPEID_APPOBJECT)
  480. {
  481. switch (parameters[i].GetType())
  482. {
  483. case VAR_VECTOR2:
  484. context->SetArgObject(i, (void *)&parameters[i].GetVector2());
  485. break;
  486. case VAR_VECTOR3:
  487. context->SetArgObject(i, (void *)&parameters[i].GetVector3());
  488. break;
  489. case VAR_VECTOR4:
  490. context->SetArgObject(i, (void *)&parameters[i].GetVector4());
  491. break;
  492. case VAR_QUATERNION:
  493. context->SetArgObject(i, (void *)&parameters[i].GetQuaternion());
  494. break;
  495. case VAR_STRING:
  496. context->SetArgObject(i, (void *)&parameters[i].GetString());
  497. break;
  498. case VAR_PTR:
  499. context->SetArgObject(i, (void *)parameters[i].GetPtr());
  500. break;
  501. default:
  502. break;
  503. }
  504. }
  505. break;
  506. }
  507. }
  508. }
  509. void ScriptFile::ReleaseModule()
  510. {
  511. if (scriptModule_)
  512. {
  513. script_->ClearObjectTypeCache();
  514. // Clear search caches and event handlers
  515. includeFiles_.Clear();
  516. validClasses_.Clear();
  517. functions_.Clear();
  518. methods_.Clear();
  519. UnsubscribeFromAllEventsExcept(PODVector<StringHash>(), true);
  520. // Remove the module
  521. scriptModule_->SetUserData(0);
  522. asIScriptEngine* engine = script_->GetScriptEngine();
  523. engine->DiscardModule(GetName().CString());
  524. scriptModule_ = 0;
  525. compiled_ = false;
  526. SetMemoryUse(0);
  527. }
  528. }
  529. void ScriptFile::HandleScriptEvent(StringHash eventType, VariantMap& eventData)
  530. {
  531. if (!compiled_)
  532. return;
  533. asIScriptFunction* function = static_cast<asIScriptFunction*>(GetEventHandler()->GetUserData());
  534. VariantVector parameters;
  535. if (function->GetParamCount() > 0)
  536. {
  537. parameters.Push(Variant((void*)&eventType));
  538. parameters.Push(Variant((void*)&eventData));
  539. }
  540. Execute(function, parameters);
  541. }
  542. ScriptFile* GetScriptContextFile()
  543. {
  544. asIScriptContext* context = asGetActiveContext();
  545. asIScriptFunction* function = context ? context->GetFunction() : 0;
  546. asIScriptModule* module = function ? function->GetEngine()->GetModule(function->GetModuleName()) : 0;
  547. if (module)
  548. return static_cast<ScriptFile*>(module->GetUserData());
  549. else
  550. return 0;
  551. }
  552. }