ScriptFile.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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 "SharedArrayPtr.h"
  31. #include "StringUtils.h"
  32. #include <angelscript.h>
  33. #include <cstring>
  34. #include "DebugNew.h"
  35. static const int MAX_NESTING_LEVEL = 32;
  36. static int executeNestingLevel = 0;
  37. ScriptFile* lastScriptFile = 0;
  38. ScriptFile::ScriptFile(ScriptEngine* scriptEngine, const std::string& name) :
  39. Resource(name),
  40. mScriptEngine(scriptEngine),
  41. mScriptModule(0),
  42. mScriptContext(0),
  43. mCompiled(false)
  44. {
  45. if (!mScriptEngine)
  46. EXCEPTION("Null script engine for ScriptFile");
  47. }
  48. ScriptFile::~ScriptFile()
  49. {
  50. if (mScriptModule)
  51. {
  52. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  53. engine->DiscardModule(getName().c_str());
  54. mScriptModule = 0;
  55. }
  56. if (mScriptContext)
  57. {
  58. mScriptContext->Release();
  59. mScriptContext = 0;
  60. }
  61. if (lastScriptFile == this)
  62. lastScriptFile = 0;
  63. }
  64. void ScriptFile::load(Deserializer& source, ResourceCache* cache)
  65. {
  66. PROFILE(Script_Load);
  67. // Discard the previous module if there was one
  68. mCompiled = false;
  69. mAllIncludeFiles.clear();
  70. setMemoryUse(0);
  71. removeAllEventHandlers();
  72. // Create the module
  73. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  74. mScriptModule = engine->GetModule(getName().c_str(), asGM_ALWAYS_CREATE);
  75. if (!mScriptModule)
  76. EXCEPTION("Failed to create script module " + getName());
  77. // Add the initial section and check for includes
  78. addScriptSection(engine, source, cache);
  79. // Compile
  80. if (mScriptModule->Build() < 0)
  81. EXCEPTION("Failed to build script module " + getName());
  82. LOGINFO("Compiled script module " + getName());
  83. mCompiled = true;
  84. }
  85. void ScriptFile::addEventHandler(StringHash eventType, const std::string& handlerName)
  86. {
  87. if (!mCompiled)
  88. return;
  89. std::string declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  90. asIScriptFunction* function = getFunction(declaration);
  91. if (!function)
  92. {
  93. LOGERROR("Event handler function " + declaration + " not found in " + getName());
  94. return;
  95. }
  96. subscribeToEvent(eventType, EVENT_HANDLER(ScriptFile, handleScriptEvent));
  97. mEventHandlers[eventType] = function;
  98. // Create a context for script event handling if does not exist already
  99. if (!mScriptContext)
  100. mScriptContext = mScriptEngine->createScriptContext();
  101. }
  102. bool ScriptFile::execute(const std::string& declaration, asIScriptContext* context, const std::vector<Variant>& parameters)
  103. {
  104. asIScriptFunction* function = getFunction(declaration);
  105. if (!function)
  106. {
  107. LOGERROR("Function " + declaration + " not found in " + getName());
  108. return false;
  109. }
  110. return execute(getFunction(declaration), context, parameters);
  111. }
  112. bool ScriptFile::execute(asIScriptFunction* function, asIScriptContext* context, const std::vector<Variant>& parameters)
  113. {
  114. PROFILE(Script_ExecuteFunction);
  115. if ((!mCompiled) || (!function))
  116. return false;
  117. if (!context)
  118. context = mScriptEngine->getImmediateContext();
  119. if (context->GetState() != asEXECUTION_ACTIVE)
  120. {
  121. if (context->Prepare(function->GetId()) < 0)
  122. return false;
  123. lastScriptFile = this;
  124. setParameters(context, function, parameters);
  125. return context->Execute() >= 0;
  126. }
  127. else
  128. {
  129. // Prevent endless loop by nested script event handling
  130. if (executeNestingLevel > MAX_NESTING_LEVEL)
  131. {
  132. LOGERROR("Maximum script execution nesting level exceeded");
  133. return false;
  134. }
  135. // If context is active, allocate a temp context to allow nested execution.
  136. // This is not recommended for performance reasons
  137. LOGDEBUG("Executing " + std::string(function->GetDeclaration()) + " in a temporary script context");
  138. asIScriptContext* tempContext = mScriptEngine->createScriptContext();
  139. tempContext->SetUserData(context->GetUserData());
  140. if (tempContext->Prepare(function->GetId()) < 0)
  141. {
  142. tempContext->Release();
  143. return false;
  144. }
  145. lastScriptFile = this;
  146. setParameters(tempContext, function, parameters);
  147. ++executeNestingLevel;
  148. bool success = tempContext->Execute() >= 0;
  149. tempContext->Release();
  150. --executeNestingLevel;
  151. return success;
  152. }
  153. }
  154. bool ScriptFile::execute(asIScriptObject* object, const std::string& declaration, asIScriptContext* context, const std::vector<Variant>& parameters)
  155. {
  156. asIScriptFunction* method = getMethod(object, declaration);
  157. if (!method)
  158. {
  159. LOGERROR("Method " + declaration + " not found in " + getName());
  160. return false;
  161. }
  162. return execute(object, method, context, parameters);
  163. }
  164. bool ScriptFile::execute(asIScriptObject* object, asIScriptFunction* method, asIScriptContext* context,
  165. const std::vector<Variant>& parameters)
  166. {
  167. PROFILE(Script_ExecuteMethod);
  168. if ((!mCompiled) || (!object) || (!method))
  169. return false;
  170. if (!context)
  171. context = mScriptEngine->getImmediateContext();
  172. if (context->GetState() != asEXECUTION_ACTIVE)
  173. {
  174. if (context->Prepare(method->GetId()) < 0)
  175. return false;
  176. context->SetObject(object);
  177. setParameters(context, method, parameters);
  178. return context->Execute() >= 0;
  179. }
  180. else
  181. {
  182. // Prevent endless loop by nested script event handling
  183. if (executeNestingLevel > MAX_NESTING_LEVEL)
  184. {
  185. LOGERROR("Maximum script execution nesting level exceeded");
  186. return false;
  187. }
  188. // If context is active, allocate a temp context to allow nested execution.
  189. // This is not recommended for performance reasons
  190. LOGDEBUG("Executing " + std::string(method->GetDeclaration()) + " in a temporary script context");
  191. asIScriptContext* tempContext = mScriptEngine->createScriptContext();
  192. tempContext->SetUserData(context->GetUserData());
  193. if (tempContext->Prepare(method->GetId()) < 0)
  194. {
  195. tempContext->Release();
  196. return false;
  197. }
  198. tempContext->SetObject(object);
  199. setParameters(tempContext, method, parameters);
  200. ++executeNestingLevel;
  201. bool success = tempContext->Execute() >= 0;
  202. tempContext->Release();
  203. --executeNestingLevel;
  204. return success;
  205. }
  206. }
  207. asIScriptObject* ScriptFile::createObject(const std::string& className, asIScriptContext* context)
  208. {
  209. PROFILE(Script_CreateObject);
  210. if (!isCompiled())
  211. return 0;
  212. if (!context)
  213. context = mScriptEngine->getImmediateContext();
  214. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  215. asIObjectType *type = engine->GetObjectTypeById(mScriptModule->GetTypeIdByDecl(className.c_str()));
  216. if (!type)
  217. return 0;
  218. // Get the factory function id from the object type
  219. std::string factoryName = className + "@ " + className + "()";
  220. int factoryId = type->GetFactoryIdByDecl(factoryName.c_str());
  221. if (factoryId < 0)
  222. return 0;
  223. if (context->Prepare(factoryId) < 0)
  224. return 0;
  225. if (context->Execute() < 0)
  226. return 0;
  227. asIScriptObject* obj = *(static_cast<asIScriptObject**>(context->GetAddressOfReturnValue()));
  228. if (obj)
  229. obj->AddRef();
  230. return obj;
  231. }
  232. asIScriptFunction* ScriptFile::getFunction(const std::string& declaration) const
  233. {
  234. if (!mCompiled)
  235. return 0;
  236. int id = mScriptModule->GetFunctionIdByDecl(declaration.c_str());
  237. return mScriptModule->GetFunctionDescriptorById(id);
  238. }
  239. asIScriptFunction* ScriptFile::getMethod(asIScriptObject* object, const std::string& declaration) const
  240. {
  241. if ((!mCompiled) || (!object))
  242. return 0;
  243. asIObjectType* type = object->GetObjectType();
  244. if (!type)
  245. return 0;
  246. int id = type->GetMethodIdByDecl(declaration.c_str());
  247. return mScriptModule->GetFunctionDescriptorById(id);
  248. }
  249. void ScriptFile::addScriptSection(asIScriptEngine* engine, Deserializer& source, ResourceCache* cache)
  250. {
  251. unsigned dataSize = source.getSize();
  252. SharedArrayPtr<char> buffer(new char[dataSize]);
  253. source.read((void*)buffer.getPtr(), dataSize);
  254. // Pre-parse for includes
  255. // Adapted from Angelscript's scriptbuilder add-on
  256. std::vector<std::string> includeFiles;
  257. unsigned pos = 0;
  258. while(pos < dataSize)
  259. {
  260. int len;
  261. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  262. if ((t == asTC_COMMENT) || (t == asTC_WHITESPACE))
  263. {
  264. pos += len;
  265. continue;
  266. }
  267. // Is this a preprocessor directive?
  268. if (buffer[pos] == '#')
  269. {
  270. int start = pos++;
  271. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  272. if (t == asTC_IDENTIFIER)
  273. {
  274. std::string token(&buffer[pos], len);
  275. if (token == "include")
  276. {
  277. pos += len;
  278. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  279. if (t == asTC_WHITESPACE)
  280. {
  281. pos += len;
  282. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  283. }
  284. if ((t == asTC_VALUE) && (len > 2) && (buffer[pos] == '"'))
  285. {
  286. // Get the include file
  287. std::string includeFile(&buffer[pos+1], len - 2);
  288. pos += len;
  289. // If the file is not found as it is, add the path of current file
  290. if (!cache->exists(includeFile))
  291. includeFile = getPath(getName()) + includeFile;
  292. std::string includeFileLower = toLower(includeFile);
  293. // If not included yet, store it for later processing
  294. if (mAllIncludeFiles.find(includeFileLower) == mAllIncludeFiles.end())
  295. {
  296. mAllIncludeFiles.insert(includeFileLower);
  297. includeFiles.push_back(includeFile);
  298. }
  299. // Overwrite the include directive with space characters to avoid compiler error
  300. memset(&buffer[start], ' ', pos - start);
  301. }
  302. }
  303. }
  304. }
  305. // Don't search includes within statement blocks or between tokens in statements
  306. else
  307. {
  308. int len;
  309. // Skip until ; or { whichever comes first
  310. while ((pos < dataSize) && (buffer[pos] != ';') && (buffer[pos] != '{' ))
  311. {
  312. engine->ParseToken(&buffer[pos], 0, &len);
  313. pos += len;
  314. }
  315. // Skip entire statement block
  316. if ((pos < dataSize) && (buffer[pos] == '{' ))
  317. {
  318. ++pos;
  319. // Find the end of the statement block
  320. int level = 1;
  321. while ((level > 0) && (pos < dataSize))
  322. {
  323. asETokenClass t = engine->ParseToken(&buffer[pos], 0, &len);
  324. if (t == asTC_KEYWORD)
  325. {
  326. if (buffer[pos] == '{')
  327. level++;
  328. else if(buffer[pos] == '}')
  329. level--;
  330. }
  331. pos += len;
  332. }
  333. }
  334. else
  335. ++pos;
  336. }
  337. }
  338. // Process includes first
  339. for (unsigned i = 0; i < includeFiles.size(); ++i)
  340. {
  341. SharedPtr<File> file = cache->getFile(includeFiles[i]);
  342. addScriptSection(engine, *file, cache);
  343. }
  344. // Then add this section
  345. if (mScriptModule->AddScriptSection(source.getName().c_str(), (const char*)buffer.getPtr(), dataSize) < 0)
  346. EXCEPTION("Failed to add script section " + source.getName());
  347. setMemoryUse(getMemoryUse() + dataSize);
  348. }
  349. void ScriptFile::setParameters(asIScriptContext* context, asIScriptFunction* function, const std::vector<Variant>& parameters)
  350. {
  351. unsigned paramCount = function->GetParamCount();
  352. for (unsigned i = 0; (i < parameters.size()) && (i < paramCount); ++i)
  353. {
  354. int paramType = function->GetParamTypeId(i);
  355. switch (paramType)
  356. {
  357. case asTYPEID_BOOL:
  358. context->SetArgByte(i, (unsigned char)parameters[i].getBool());
  359. break;
  360. case asTYPEID_INT8:
  361. case asTYPEID_UINT8:
  362. context->SetArgByte(i, parameters[i].getInt());
  363. break;
  364. case asTYPEID_INT16:
  365. case asTYPEID_UINT16:
  366. context->SetArgWord(i, parameters[i].getInt());
  367. break;
  368. case asTYPEID_INT32:
  369. case asTYPEID_UINT32:
  370. context->SetArgDWord(i, parameters[i].getInt());
  371. break;
  372. case asTYPEID_FLOAT:
  373. context->SetArgFloat(i, parameters[i].getFloat());
  374. break;
  375. default:
  376. if (paramType & asTYPEID_APPOBJECT)
  377. {
  378. switch (parameters[i].getType())
  379. {
  380. case VAR_VECTOR2:
  381. context->SetArgObject(i, (void *)&parameters[i].getVector2());
  382. break;
  383. case VAR_VECTOR3:
  384. context->SetArgObject(i, (void *)&parameters[i].getVector3());
  385. break;
  386. case VAR_VECTOR4:
  387. context->SetArgObject(i, (void *)&parameters[i].getVector4());
  388. break;
  389. case VAR_QUATERNION:
  390. context->SetArgObject(i, (void *)&parameters[i].getQuaternion());
  391. break;
  392. case VAR_STRING:
  393. context->SetArgObject(i, (void *)&parameters[i].getString());
  394. break;
  395. case VAR_PTR:
  396. context->SetArgObject(i, (void *)parameters[i].getPtr());
  397. break;
  398. }
  399. }
  400. break;
  401. }
  402. }
  403. }
  404. void ScriptFile::handleScriptEvent(StringHash eventType, VariantMap& eventData)
  405. {
  406. if (!mCompiled)
  407. return;
  408. std::map<StringHash, asIScriptFunction*>::iterator i = mEventHandlers.find(eventType);
  409. if (i == mEventHandlers.end())
  410. return;
  411. std::vector<Variant> parameters;
  412. parameters.push_back(Variant((void*)&eventType));
  413. parameters.push_back(Variant((void*)&eventData));
  414. execute(i->second, mScriptContext, parameters);
  415. }
  416. ScriptFile* getLastScriptFile()
  417. {
  418. return lastScriptFile;
  419. }