ScriptFile.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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 "File.h"
  25. #include "Log.h"
  26. #include "Profiler.h"
  27. #include "ResourceCache.h"
  28. #include "ScriptEngine.h"
  29. #include "ScriptFile.h"
  30. #include "ScriptInstance.h"
  31. #include "SharedArrayPtr.h"
  32. #include "StringUtils.h"
  33. #include <angelscript.h>
  34. #include <cstring>
  35. #include "DebugNew.h"
  36. static unsigned scriptNestingLevel = 0;
  37. std::map<asIScriptModule*, ScriptFile*> moduleToFile;
  38. ScriptFile::ScriptFile(ScriptEngine* scriptEngine, const std::string& name) :
  39. Resource(name),
  40. mScriptEngine(scriptEngine),
  41. mScriptModule(0),
  42. mCompiled(false)
  43. {
  44. if (!mScriptEngine)
  45. EXCEPTION("Null script engine for ScriptFile");
  46. }
  47. ScriptFile::~ScriptFile()
  48. {
  49. releaseModule();
  50. }
  51. void ScriptFile::load(Deserializer& source, ResourceCache* cache)
  52. {
  53. PROFILE(Script_Load);
  54. releaseModule();
  55. // Create the module. Discard previous module if there was one
  56. if (mScriptModule)
  57. moduleToFile.erase(mScriptModule);
  58. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  59. mScriptModule = engine->GetModule(getName().c_str(), asGM_ALWAYS_CREATE);
  60. if (!mScriptModule)
  61. EXCEPTION("Failed to create script module " + getName());
  62. // Add the initial section and check for includes
  63. addScriptSection(engine, source, cache);
  64. // Compile. Set script engine logging to retained mode so that potential exceptions can show all error info
  65. mScriptEngine->setLogMode(LOGMODE_RETAINED);
  66. mScriptEngine->clearLogMessages();
  67. int result = mScriptModule->Build();
  68. std::string errors = mScriptEngine->getLogMessages();
  69. mScriptEngine->setLogMode(LOGMODE_IMMEDIATE);
  70. if (result < 0)
  71. EXCEPTION("Failed to compile script module " + getName() + ":\n" + errors);
  72. if (!errors.empty())
  73. LOGWARNING(errors);
  74. LOGINFO("Compiled script module " + getName());
  75. mCompiled = true;
  76. moduleToFile[mScriptModule] = this;
  77. }
  78. void ScriptFile::addEventHandler(StringHash eventType, const std::string& handlerName)
  79. {
  80. if (!mCompiled)
  81. return;
  82. std::string declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  83. asIScriptFunction* function = getFunction(declaration);
  84. if (!function)
  85. {
  86. declaration = "void " + handlerName + "()";
  87. function = getFunction(declaration);
  88. if (!function)
  89. {
  90. LOGERROR("Event handler function " + handlerName + " not found in " + getName());
  91. return;
  92. }
  93. }
  94. subscribeToEvent(eventType, EVENT_HANDLER_USERDATA(ScriptFile, handleScriptEvent, (void*)function));
  95. }
  96. void ScriptFile::addEventHandler(EventListener* sender, StringHash eventType, const std::string& handlerName)
  97. {
  98. if (!mCompiled)
  99. return;
  100. if (!sender)
  101. {
  102. LOGERROR("Null event sender for event " + toString(eventType) + ", handler " + handlerName);
  103. return;
  104. }
  105. std::string declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  106. asIScriptFunction* function = getFunction(declaration);
  107. if (!function)
  108. {
  109. declaration = "void " + handlerName + "()";
  110. function = getFunction(declaration);
  111. if (!function)
  112. {
  113. LOGERROR("Event handler function " + handlerName + " not found in " + getName());
  114. return;
  115. }
  116. }
  117. subscribeToEvent(sender, eventType, EVENT_HANDLER_USERDATA(ScriptFile, handleScriptEvent, (void*)function));
  118. }
  119. bool ScriptFile::execute(const std::string& declaration, const VariantVector& parameters, bool unprepare)
  120. {
  121. asIScriptFunction* function = getFunction(declaration);
  122. if (!function)
  123. {
  124. LOGERROR("Function " + declaration + " not found in " + getName());
  125. return false;
  126. }
  127. return execute(getFunction(declaration), parameters, unprepare);
  128. }
  129. bool ScriptFile::execute(asIScriptFunction* function, const VariantVector& parameters, bool unprepare)
  130. {
  131. PROFILE(Script_ExecuteFunction);
  132. if ((!mCompiled) || (!function))
  133. return false;
  134. // Prevent endless loop by nested script execution
  135. if (scriptNestingLevel >= MAX_SCRIPT_NESTING_LEVEL)
  136. {
  137. LOGERROR("Maximum script execution nesting level exceeded");
  138. return false;
  139. }
  140. asIScriptContext* context = mScriptEngine->getScriptFileContext(scriptNestingLevel);
  141. if (context->Prepare(function->GetId()) < 0)
  142. return false;
  143. setParameters(context, function, parameters);
  144. ++scriptNestingLevel;
  145. bool success = context->Execute() >= 0;
  146. if (unprepare)
  147. context->Unprepare();
  148. --scriptNestingLevel;
  149. return success;
  150. }
  151. bool ScriptFile::execute(asIScriptObject* object, const std::string& declaration, const VariantVector& parameters, bool unprepare)
  152. {
  153. asIScriptFunction* method = getMethod(object, declaration);
  154. if (!method)
  155. {
  156. LOGERROR("Method " + declaration + " not found in " + getName());
  157. return false;
  158. }
  159. return execute(object, method, parameters, unprepare);
  160. }
  161. bool ScriptFile::execute(asIScriptObject* object, asIScriptFunction* method, const VariantVector& parameters, bool unprepare)
  162. {
  163. PROFILE(Script_ExecuteMethod);
  164. if ((!mCompiled) || (!object) || (!method))
  165. return false;
  166. // Prevent endless loop by nested script execution
  167. if (scriptNestingLevel >= MAX_SCRIPT_NESTING_LEVEL)
  168. {
  169. LOGERROR("Maximum script execution nesting level exceeded");
  170. return false;
  171. }
  172. asIScriptContext* context = mScriptEngine->getScriptFileContext(scriptNestingLevel);
  173. // If context is active, allocate a temp context to allow nested execution.
  174. if (context->Prepare(method->GetId()) < 0)
  175. return false;
  176. context->SetObject(object);
  177. setParameters(context, method, parameters);
  178. ++scriptNestingLevel;
  179. bool success = context->Execute() >= 0;
  180. if (unprepare)
  181. context->Unprepare();
  182. --scriptNestingLevel;
  183. return success;
  184. }
  185. asIScriptObject* ScriptFile::createObject(const std::string& className)
  186. {
  187. PROFILE(Script_CreateObject);
  188. if (!isCompiled())
  189. return 0;
  190. // Prevent endless loop by nested script execution
  191. if (scriptNestingLevel >= MAX_SCRIPT_NESTING_LEVEL)
  192. {
  193. LOGERROR("Maximum script execution nesting level exceeded, can not create object");
  194. return 0;
  195. }
  196. asIScriptContext* context = mScriptEngine->getScriptFileContext(scriptNestingLevel);
  197. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  198. asIObjectType *type = engine->GetObjectTypeById(mScriptModule->GetTypeIdByDecl(className.c_str()));
  199. if (!type)
  200. return 0;
  201. // Ensure that the type implements the "ScriptObject" interface, so it can be returned to script properly
  202. bool found = false;
  203. std::map<asIObjectType*, bool>::const_iterator i = mCheckedClasses.find(type);
  204. if (i != mCheckedClasses.end())
  205. found = i->second;
  206. else
  207. {
  208. unsigned numInterfaces = type->GetInterfaceCount();
  209. for (unsigned j = 0; j < numInterfaces; ++j)
  210. {
  211. asIObjectType* interfaceType = type->GetInterface(j);
  212. if (!strcmp(interfaceType->GetName(), "ScriptObject"))
  213. {
  214. found = true;
  215. break;
  216. }
  217. }
  218. mCheckedClasses[type] = found;
  219. }
  220. if (!found)
  221. {
  222. LOGERROR("Script class " + className + " does not implement the ScriptObject interface");
  223. return 0;
  224. }
  225. // Get the factory function id from the object type
  226. std::string factoryName = className + "@ " + className + "()";
  227. int factoryId = type->GetFactoryIdByDecl(factoryName.c_str());
  228. if (factoryId < 0)
  229. return 0;
  230. if (context->Prepare(factoryId) < 0)
  231. return 0;
  232. if (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 std::string& declaration)
  240. {
  241. if (!mCompiled)
  242. return 0;
  243. std::map<std::string, asIScriptFunction*>::const_iterator i = mFunctions.find(declaration);
  244. if (i != mFunctions.end())
  245. return i->second;
  246. int id = mScriptModule->GetFunctionIdByDecl(declaration.c_str());
  247. asIScriptFunction* function = mScriptModule->GetFunctionDescriptorById(id);
  248. mFunctions[declaration] = function;
  249. return function;
  250. }
  251. asIScriptFunction* ScriptFile::getMethod(asIScriptObject* object, const std::string& declaration)
  252. {
  253. if ((!mCompiled) || (!object))
  254. return 0;
  255. asIObjectType* type = object->GetObjectType();
  256. if (!type)
  257. return 0;
  258. std::map<asIObjectType*, std::map<std::string, asIScriptFunction*> >::const_iterator i = mMethods.find(type);
  259. if (i != mMethods.end())
  260. {
  261. std::map<std::string, asIScriptFunction*>::const_iterator j = i->second.find(declaration);
  262. if (j != i->second.end())
  263. return j->second;
  264. }
  265. int id = type->GetMethodIdByDecl(declaration.c_str());
  266. asIScriptFunction* function = mScriptModule->GetFunctionDescriptorById(id);
  267. mMethods[type][declaration] = function;
  268. return function;
  269. }
  270. void ScriptFile::addScriptSection(asIScriptEngine* engine, Deserializer& source, ResourceCache* cache)
  271. {
  272. unsigned dataSize = source.getSize();
  273. SharedArrayPtr<char> buffer(new char[dataSize]);
  274. source.read((void*)buffer.getPtr(), dataSize);
  275. // Pre-parse for includes
  276. // Adapted from Angelscript's scriptbuilder add-on
  277. std::vector<std::string> includeFiles;
  278. unsigned pos = 0;
  279. while(pos < dataSize)
  280. {
  281. int len;
  282. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  283. if ((t == asTC_COMMENT) || (t == asTC_WHITESPACE))
  284. {
  285. pos += len;
  286. continue;
  287. }
  288. // Is this a preprocessor directive?
  289. if (buffer[pos] == '#')
  290. {
  291. int start = pos++;
  292. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  293. if (t == asTC_IDENTIFIER)
  294. {
  295. std::string token(&buffer[pos], len);
  296. if (token == "include")
  297. {
  298. pos += len;
  299. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  300. if (t == asTC_WHITESPACE)
  301. {
  302. pos += len;
  303. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  304. }
  305. if ((t == asTC_VALUE) && (len > 2) && (buffer[pos] == '"'))
  306. {
  307. // Get the include file
  308. std::string includeFile(&buffer[pos+1], len - 2);
  309. pos += len;
  310. // If the file is not found as it is, add the path of current file
  311. if (!cache->exists(includeFile))
  312. includeFile = getPath(getName()) + includeFile;
  313. std::string includeFileLower = toLower(includeFile);
  314. // If not included yet, store it for later processing
  315. if (mAllIncludeFiles.find(includeFileLower) == mAllIncludeFiles.end())
  316. {
  317. mAllIncludeFiles.insert(includeFileLower);
  318. includeFiles.push_back(includeFile);
  319. }
  320. // Overwrite the include directive with space characters to avoid compiler error
  321. memset(&buffer[start], ' ', pos - start);
  322. }
  323. }
  324. }
  325. }
  326. // Don't search includes within statement blocks or between tokens in statements
  327. else
  328. {
  329. int len;
  330. // Skip until ; or { whichever comes first
  331. while ((pos < dataSize) && (buffer[pos] != ';') && (buffer[pos] != '{' ))
  332. {
  333. engine->ParseToken(&buffer[pos], 0, &len);
  334. pos += len;
  335. }
  336. // Skip entire statement block
  337. if ((pos < dataSize) && (buffer[pos] == '{' ))
  338. {
  339. ++pos;
  340. // Find the end of the statement block
  341. int level = 1;
  342. while ((level > 0) && (pos < dataSize))
  343. {
  344. asETokenClass t = engine->ParseToken(&buffer[pos], 0, &len);
  345. if (t == asTC_KEYWORD)
  346. {
  347. if (buffer[pos] == '{')
  348. level++;
  349. else if(buffer[pos] == '}')
  350. level--;
  351. }
  352. pos += len;
  353. }
  354. }
  355. else
  356. ++pos;
  357. }
  358. }
  359. // Process includes first
  360. for (unsigned i = 0; i < includeFiles.size(); ++i)
  361. {
  362. SharedPtr<File> file = cache->getFile(includeFiles[i]);
  363. addScriptSection(engine, *file, cache);
  364. }
  365. // Then add this section
  366. if (mScriptModule->AddScriptSection(source.getName().c_str(), (const char*)buffer.getPtr(), dataSize) < 0)
  367. EXCEPTION("Failed to add script section " + source.getName());
  368. setMemoryUse(getMemoryUse() + dataSize);
  369. }
  370. void ScriptFile::setParameters(asIScriptContext* context, asIScriptFunction* function, const VariantVector& parameters)
  371. {
  372. unsigned paramCount = function->GetParamCount();
  373. for (unsigned i = 0; (i < parameters.size()) && (i < paramCount); ++i)
  374. {
  375. int paramType = function->GetParamTypeId(i);
  376. switch (paramType)
  377. {
  378. case asTYPEID_BOOL:
  379. context->SetArgByte(i, (unsigned char)parameters[i].getBool());
  380. break;
  381. case asTYPEID_INT8:
  382. case asTYPEID_UINT8:
  383. context->SetArgByte(i, parameters[i].getInt());
  384. break;
  385. case asTYPEID_INT16:
  386. case asTYPEID_UINT16:
  387. context->SetArgWord(i, parameters[i].getInt());
  388. break;
  389. case asTYPEID_INT32:
  390. case asTYPEID_UINT32:
  391. context->SetArgDWord(i, parameters[i].getInt());
  392. break;
  393. case asTYPEID_FLOAT:
  394. context->SetArgFloat(i, parameters[i].getFloat());
  395. break;
  396. default:
  397. if (paramType & asTYPEID_APPOBJECT)
  398. {
  399. switch (parameters[i].getType())
  400. {
  401. case VAR_VECTOR2:
  402. context->SetArgObject(i, (void *)&parameters[i].getVector2());
  403. break;
  404. case VAR_VECTOR3:
  405. context->SetArgObject(i, (void *)&parameters[i].getVector3());
  406. break;
  407. case VAR_VECTOR4:
  408. context->SetArgObject(i, (void *)&parameters[i].getVector4());
  409. break;
  410. case VAR_QUATERNION:
  411. context->SetArgObject(i, (void *)&parameters[i].getQuaternion());
  412. break;
  413. case VAR_STRING:
  414. context->SetArgObject(i, (void *)&parameters[i].getString());
  415. break;
  416. case VAR_PTR:
  417. context->SetArgObject(i, (void *)parameters[i].getPtr());
  418. break;
  419. }
  420. }
  421. break;
  422. }
  423. }
  424. }
  425. void ScriptFile::releaseModule()
  426. {
  427. if (mScriptModule)
  428. {
  429. // Clear search caches, event handlers and function-to-file mappings
  430. mAllIncludeFiles.clear();
  431. mCheckedClasses.clear();
  432. mFunctions.clear();
  433. mMethods.clear();
  434. removeAllEventHandlers();
  435. // Perform a full garbage collection cycle now
  436. mScriptEngine->garbageCollect(true);
  437. // Remove the module
  438. moduleToFile.erase(mScriptModule);
  439. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  440. engine->DiscardModule(getName().c_str());
  441. mScriptModule = 0;
  442. mCompiled = false;
  443. setMemoryUse(0);
  444. }
  445. }
  446. void ScriptFile::handleScriptEvent(StringHash eventType, VariantMap& eventData)
  447. {
  448. if (!mCompiled)
  449. return;
  450. asIScriptFunction* function = static_cast<asIScriptFunction*>(getInvoker()->getUserData());
  451. VariantVector parameters;
  452. if (function->GetParamCount() > 0)
  453. {
  454. parameters.push_back(Variant((void*)&eventType));
  455. parameters.push_back(Variant((void*)&eventData));
  456. }
  457. execute(function, parameters);
  458. }
  459. ScriptFile* getScriptContextFile()
  460. {
  461. asIScriptFunction* function = asGetActiveContext()->GetFunction();
  462. asIScriptModule* module = function->GetEngine()->GetModule(function->GetModuleName());
  463. std::map<asIScriptModule*, ScriptFile*>::const_iterator i = moduleToFile.find(module);
  464. if (i != moduleToFile.end())
  465. return i->second;
  466. else
  467. return 0;
  468. }
  469. unsigned getScriptNestingLevel()
  470. {
  471. return scriptNestingLevel;
  472. }