ScriptFile.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "ArrayPtr.h"
  25. #include "Context.h"
  26. #include "FileSystem.h"
  27. #include "Log.h"
  28. #include "Profiler.h"
  29. #include "ResourceCache.h"
  30. #include "Script.h"
  31. #include "ScriptFile.h"
  32. #include "ScriptInstance.h"
  33. #include <angelscript.h>
  34. #include <cstring>
  35. #include "DebugNew.h"
  36. OBJECTTYPESTATIC(ScriptFile);
  37. ScriptFile::ScriptFile(Context* context) :
  38. Resource(context),
  39. script_(GetSubsystem<Script>()),
  40. scriptModule_(0),
  41. compiled_(false)
  42. {
  43. }
  44. ScriptFile::~ScriptFile()
  45. {
  46. ReleaseModule();
  47. }
  48. void ScriptFile::RegisterObject(Context* context)
  49. {
  50. context->RegisterFactory<ScriptFile>();
  51. }
  52. bool ScriptFile::Load(Deserializer& source)
  53. {
  54. PROFILE(LoadScript);
  55. ReleaseModule();
  56. // Create the module. Discard previous module if there was one
  57. if (scriptModule_)
  58. script_->GetModuleMap().Erase(scriptModule_);
  59. asIScriptEngine* engine = script_->GetScriptEngine();
  60. scriptModule_ = engine->GetModule(GetName().CString(), asGM_ALWAYS_CREATE);
  61. if (!scriptModule_)
  62. {
  63. LOGERROR("Failed to create script module " + GetName());
  64. return false;
  65. }
  66. // Add the initial section and check for includes
  67. if (!AddScriptSection(engine, source))
  68. return false;
  69. // Compile. Set script engine logging to retained mode so that potential exceptions can show all error info
  70. script_->SetLogMode(LOGMODE_RETAINED);
  71. script_->ClearLogMessages();
  72. int result = scriptModule_->Build();
  73. String errors = script_->GetLogMessages();
  74. script_->SetLogMode(LOGMODE_IMMEDIATE);
  75. if (result < 0)
  76. {
  77. LOGERROR("Failed to compile script module " + GetName() + ":\n" + errors);
  78. return false;
  79. }
  80. if (!errors.Empty())
  81. LOGWARNING(errors);
  82. LOGINFO("Compiled script module " + GetName());
  83. compiled_ = true;
  84. script_->GetModuleMap()[scriptModule_] = this;
  85. return true;
  86. }
  87. void ScriptFile::AddEventHandler(StringHash eventType, const String& handlerName)
  88. {
  89. if (!compiled_)
  90. return;
  91. String declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  92. asIScriptFunction* function = GetFunction(declaration);
  93. if (!function)
  94. {
  95. declaration = "void " + handlerName + "()";
  96. function = GetFunction(declaration);
  97. if (!function)
  98. {
  99. LOGERROR("Event handler function " + handlerName + " not found in " + GetName());
  100. return;
  101. }
  102. }
  103. SubscribeToEvent(eventType, HANDLER_USERDATA(ScriptFile, HandleScriptEvent, (void*)function));
  104. }
  105. void ScriptFile::AddEventHandler(Object* sender, StringHash eventType, const String& handlerName)
  106. {
  107. if (!compiled_)
  108. return;
  109. if (!sender)
  110. {
  111. LOGERROR("Null event sender for event " + String(eventType) + ", handler " + handlerName);
  112. return;
  113. }
  114. String declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  115. asIScriptFunction* function = GetFunction(declaration);
  116. if (!function)
  117. {
  118. declaration = "void " + handlerName + "()";
  119. function = GetFunction(declaration);
  120. if (!function)
  121. {
  122. LOGERROR("Event handler function " + handlerName + " not found in " + GetName());
  123. return;
  124. }
  125. }
  126. SubscribeToEvent(sender, eventType, HANDLER_USERDATA(ScriptFile, HandleScriptEvent, (void*)function));
  127. }
  128. bool ScriptFile::Execute(const String& declaration, const VariantVector& parameters, bool unprepare)
  129. {
  130. asIScriptFunction* function = GetFunction(declaration);
  131. if (!function)
  132. {
  133. LOGERROR("Function " + declaration + " not found in " + GetName());
  134. return false;
  135. }
  136. return Execute(GetFunction(declaration), parameters, unprepare);
  137. }
  138. bool ScriptFile::Execute(asIScriptFunction* function, const VariantVector& parameters, bool unprepare)
  139. {
  140. PROFILE(ExecuteFunction);
  141. if (!compiled_ || !function)
  142. return false;
  143. // It is possible that executing the function causes us to unload. Therefore do not rely on member variables
  144. // However, we are not prepared for the whole script system getting destroyed during execution (should never happen)
  145. Script* scriptSystem = script_;
  146. asIScriptContext* context = scriptSystem->GetScriptFileContext();
  147. if (!context)
  148. {
  149. LOGERROR("Maximum script execution nesting level exceeded");
  150. return false;
  151. }
  152. if (context->Prepare(function->GetId()) < 0)
  153. return false;
  154. SetParameters(context, function, parameters);
  155. scriptSystem->IncScriptNestingLevel();
  156. bool success = context->Execute() >= 0;
  157. if (unprepare)
  158. context->Unprepare();
  159. scriptSystem->DecScriptNestingLevel();
  160. return success;
  161. }
  162. bool ScriptFile::Execute(asIScriptObject* object, const String& declaration, const VariantVector& parameters, bool unprepare)
  163. {
  164. asIScriptFunction* method = GetMethod(object, declaration);
  165. if (!method)
  166. {
  167. LOGERROR("Method " + declaration + " not found in " + GetName());
  168. return false;
  169. }
  170. return Execute(object, method, parameters, unprepare);
  171. }
  172. bool ScriptFile::Execute(asIScriptObject* object, asIScriptFunction* method, const VariantVector& parameters, bool unprepare)
  173. {
  174. PROFILE(ExecuteMethod);
  175. if (!compiled_ || !object || !method)
  176. return false;
  177. // It is possible that executing the method causes us to unload. Therefore do not rely on member variables
  178. // However, we are not prepared for the whole script system getting destroyed during execution (should never happen)
  179. Script* scriptSystem = script_;
  180. asIScriptContext* context = scriptSystem->GetScriptFileContext();
  181. if (!context)
  182. {
  183. LOGERROR("Maximum script execution nesting level exceeded");
  184. return false;
  185. }
  186. if (context->Prepare(method->GetId()) < 0)
  187. return false;
  188. context->SetObject(object);
  189. SetParameters(context, method, parameters);
  190. scriptSystem->IncScriptNestingLevel();
  191. bool success = context->Execute() >= 0;
  192. if (unprepare)
  193. context->Unprepare();
  194. scriptSystem->DecScriptNestingLevel();
  195. return success;
  196. }
  197. asIScriptObject* ScriptFile::CreateObject(const String& className)
  198. {
  199. PROFILE(CreateObject);
  200. if (!IsCompiled())
  201. return 0;
  202. asIScriptContext* context = script_->GetScriptFileContext();
  203. if (!context)
  204. {
  205. LOGERROR("Maximum script execution nesting level exceeded, can not create object");
  206. return 0;
  207. }
  208. asIScriptEngine* engine = script_->GetScriptEngine();
  209. asIObjectType *type = engine->GetObjectTypeById(scriptModule_->GetTypeIdByDecl(className.CString()));
  210. if (!type)
  211. return 0;
  212. // Ensure that the type implements the "ScriptObject" interface, so it can be returned to script properly
  213. bool found = false;
  214. Map<asIObjectType*, bool>::ConstIterator i = checkedClasses_.Find(type);
  215. if (i != checkedClasses_.End())
  216. found = i->second_;
  217. else
  218. {
  219. unsigned numInterfaces = type->GetInterfaceCount();
  220. for (unsigned j = 0; j < numInterfaces; ++j)
  221. {
  222. asIObjectType* interfaceType = type->GetInterface(j);
  223. if (!strcmp(interfaceType->GetName(), "ScriptObject"))
  224. {
  225. found = true;
  226. break;
  227. }
  228. }
  229. checkedClasses_[type] = found;
  230. }
  231. if (!found)
  232. {
  233. LOGERROR("Script class " + className + " does not implement the ScriptObject interface");
  234. return 0;
  235. }
  236. // Get the factory function id from the object type
  237. String factoryName = className + "@ " + className + "()";
  238. int factoryId = type->GetFactoryIdByDecl(factoryName.CString());
  239. if (factoryId < 0 || context->Prepare(factoryId) < 0 || context->Execute() < 0)
  240. return 0;
  241. asIScriptObject* obj = *(static_cast<asIScriptObject**>(context->GetAddressOfReturnValue()));
  242. if (obj)
  243. obj->AddRef();
  244. return obj;
  245. }
  246. asIScriptFunction* ScriptFile::GetFunction(const String& declaration)
  247. {
  248. if (!compiled_)
  249. return 0;
  250. Map<String, asIScriptFunction*>::ConstIterator i = functions_.Find(declaration);
  251. if (i != functions_.End())
  252. return i->second_;
  253. int id = scriptModule_->GetFunctionIdByDecl(declaration.CString());
  254. asIScriptFunction* function = scriptModule_->GetFunctionDescriptorById(id);
  255. functions_[declaration] = function;
  256. return function;
  257. }
  258. asIScriptFunction* ScriptFile::GetMethod(asIScriptObject* object, const String& declaration)
  259. {
  260. if (!compiled_ || !object)
  261. return 0;
  262. asIObjectType* type = object->GetObjectType();
  263. if (!type)
  264. return 0;
  265. Map<asIObjectType*, Map<String, asIScriptFunction*> >::ConstIterator i = methods_.Find(type);
  266. if (i != methods_.End())
  267. {
  268. Map<String, asIScriptFunction*>::ConstIterator j = i->second_.Find(declaration);
  269. if (j != i->second_.End())
  270. return j->second_;
  271. }
  272. int id = type->GetMethodIdByDecl(declaration.CString());
  273. asIScriptFunction* function = scriptModule_->GetFunctionDescriptorById(id);
  274. methods_[type][declaration] = function;
  275. return function;
  276. }
  277. bool ScriptFile::AddScriptSection(asIScriptEngine* engine, Deserializer& source)
  278. {
  279. ResourceCache* cache = GetSubsystem<ResourceCache>();
  280. unsigned dataSize = source.GetSize();
  281. SharedArrayPtr<char> buffer(new char[dataSize]);
  282. source.Read((void*)buffer.Get(), dataSize);
  283. // Pre-parse for includes
  284. // Adapted from Angelscript's scriptbuilder add-on
  285. Vector<String> includeFiles;
  286. unsigned pos = 0;
  287. while(pos < dataSize)
  288. {
  289. int len;
  290. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  291. if (t == asTC_COMMENT || t == asTC_WHITESPACE)
  292. {
  293. pos += len;
  294. continue;
  295. }
  296. // Is this a preprocessor directive?
  297. if (buffer[pos] == '#')
  298. {
  299. int start = pos++;
  300. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  301. if (t == asTC_IDENTIFIER)
  302. {
  303. String token(&buffer[pos], len);
  304. if (token == "include")
  305. {
  306. pos += len;
  307. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  308. if (t == asTC_WHITESPACE)
  309. {
  310. pos += len;
  311. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  312. }
  313. if (t == asTC_VALUE && len > 2 && buffer[pos] == '"')
  314. {
  315. // Get the include file
  316. String includeFile(&buffer[pos+1], len - 2);
  317. pos += len;
  318. // If the file is not found as it is, add the path of current file
  319. if (!cache->Exists(includeFile))
  320. includeFile = GetPath(GetName()) + includeFile;
  321. String includeFileLower = includeFile.ToLower();
  322. // If not included yet, store it for later processing
  323. if (!includeFiles_.Contains(includeFileLower))
  324. {
  325. includeFiles_.Insert(includeFileLower);
  326. includeFiles.Push(includeFile);
  327. }
  328. // Overwrite the include directive with space characters to avoid compiler error
  329. memset(&buffer[start], ' ', pos - start);
  330. }
  331. }
  332. }
  333. }
  334. // Don't search includes within statement blocks or between tokens in statements
  335. else
  336. {
  337. int len;
  338. // Skip until ; or { whichever comes first
  339. while (pos < dataSize && buffer[pos] != ';' && buffer[pos] != '{')
  340. {
  341. engine->ParseToken(&buffer[pos], 0, &len);
  342. pos += len;
  343. }
  344. // Skip entire statement block
  345. if (pos < dataSize && buffer[pos] == '{')
  346. {
  347. ++pos;
  348. // Find the end of the statement block
  349. int level = 1;
  350. while (level > 0 && pos < dataSize)
  351. {
  352. asETokenClass t = engine->ParseToken(&buffer[pos], 0, &len);
  353. if (t == asTC_KEYWORD)
  354. {
  355. if (buffer[pos] == '{')
  356. level++;
  357. else if(buffer[pos] == '}')
  358. level--;
  359. }
  360. pos += len;
  361. }
  362. }
  363. else
  364. ++pos;
  365. }
  366. }
  367. // Process includes first
  368. for (unsigned i = 0; i < includeFiles.Size(); ++i)
  369. {
  370. SharedPtr<File> file = cache->GetFile(includeFiles[i]);
  371. if (file)
  372. {
  373. if (!AddScriptSection(engine, *file))
  374. return false;
  375. }
  376. else
  377. return false;
  378. }
  379. // Then add this section
  380. if (scriptModule_->AddScriptSection(source.GetName().CString(), (const char*)buffer.Get(), dataSize) < 0)
  381. {
  382. LOGERROR("Failed to add script section " + source.GetName());
  383. return false;
  384. }
  385. SetMemoryUse(GetMemoryUse() + dataSize);
  386. return true;
  387. }
  388. void ScriptFile::SetParameters(asIScriptContext* context, asIScriptFunction* function, const VariantVector& parameters)
  389. {
  390. unsigned paramCount = function->GetParamCount();
  391. for (unsigned i = 0; i < parameters.Size() && i < paramCount; ++i)
  392. {
  393. int paramType = function->GetParamTypeId(i);
  394. switch (paramType)
  395. {
  396. case asTYPEID_BOOL:
  397. context->SetArgByte(i, (unsigned char)parameters[i].GetBool());
  398. break;
  399. case asTYPEID_INT8:
  400. case asTYPEID_UINT8:
  401. context->SetArgByte(i, parameters[i].GetInt());
  402. break;
  403. case asTYPEID_INT16:
  404. case asTYPEID_UINT16:
  405. context->SetArgWord(i, parameters[i].GetInt());
  406. break;
  407. case asTYPEID_INT32:
  408. case asTYPEID_UINT32:
  409. context->SetArgDWord(i, parameters[i].GetInt());
  410. break;
  411. case asTYPEID_FLOAT:
  412. context->SetArgFloat(i, parameters[i].GetFloat());
  413. break;
  414. default:
  415. if (paramType & asTYPEID_APPOBJECT)
  416. {
  417. switch (parameters[i].GetType())
  418. {
  419. case VAR_VECTOR2:
  420. context->SetArgObject(i, (void *)&parameters[i].GetVector2());
  421. break;
  422. case VAR_VECTOR3:
  423. context->SetArgObject(i, (void *)&parameters[i].GetVector3());
  424. break;
  425. case VAR_VECTOR4:
  426. context->SetArgObject(i, (void *)&parameters[i].GetVector4());
  427. break;
  428. case VAR_QUATERNION:
  429. context->SetArgObject(i, (void *)&parameters[i].GetQuaternion());
  430. break;
  431. case VAR_STRING:
  432. context->SetArgObject(i, (void *)&parameters[i].GetString());
  433. break;
  434. case VAR_PTR:
  435. context->SetArgObject(i, (void *)parameters[i].GetPtr());
  436. break;
  437. default:
  438. break;
  439. }
  440. }
  441. break;
  442. }
  443. }
  444. }
  445. void ScriptFile::ReleaseModule()
  446. {
  447. if (scriptModule_)
  448. {
  449. // Clear search caches, event handlers and function-to-file mappings
  450. includeFiles_.Clear();
  451. checkedClasses_.Clear();
  452. functions_.Clear();
  453. methods_.Clear();
  454. UnsubscribeFromAllEventsWithUserData();
  455. // Remove the module
  456. script_->GetModuleMap().Erase(scriptModule_);
  457. asIScriptEngine* engine = script_->GetScriptEngine();
  458. engine->DiscardModule(GetName().CString());
  459. scriptModule_ = 0;
  460. compiled_ = false;
  461. SetMemoryUse(0);
  462. }
  463. }
  464. void ScriptFile::HandleScriptEvent(StringHash eventType, VariantMap& eventData)
  465. {
  466. if (!compiled_)
  467. return;
  468. asIScriptFunction* function = static_cast<asIScriptFunction*>(context_->GetEventHandler()->GetUserData());
  469. VariantVector parameters;
  470. if (function->GetParamCount() > 0)
  471. {
  472. parameters.Push(Variant((void*)&eventType));
  473. parameters.Push(Variant((void*)&eventData));
  474. }
  475. Execute(function, parameters);
  476. }
  477. ScriptFile* GetScriptContextFile()
  478. {
  479. asIScriptContext* context = asGetActiveContext();
  480. asIScriptFunction* function = context->GetFunction();
  481. asIScriptModule* module = function->GetEngine()->GetModule(function->GetModuleName());
  482. Map<asIScriptModule*, ScriptFile*>& moduleMap = static_cast<Script*>(context->GetEngine()->GetUserData())->GetModuleMap();
  483. Map<asIScriptModule*, ScriptFile*>::ConstIterator i = moduleMap.Find(module);
  484. if (i != moduleMap.End())
  485. return i->second_;
  486. else
  487. return 0;
  488. }