ScriptFile.cpp 19 KB

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