ScriptFile.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. if (tempContext->Prepare(function->GetId()) < 0)
  140. {
  141. tempContext->Release();
  142. return false;
  143. }
  144. lastScriptFile = this;
  145. setParameters(tempContext, function, parameters);
  146. ++executeNestingLevel;
  147. bool success = tempContext->Execute() >= 0;
  148. tempContext->Release();
  149. --executeNestingLevel;
  150. return success;
  151. }
  152. }
  153. bool ScriptFile::execute(asIScriptObject* object, const std::string& declaration, asIScriptContext* context, const std::vector<Variant>& parameters)
  154. {
  155. asIScriptFunction* method = getMethod(object, declaration);
  156. if (!method)
  157. {
  158. LOGERROR("Method " + declaration + " not found in " + getName());
  159. return false;
  160. }
  161. return execute(object, method, context, parameters);
  162. }
  163. bool ScriptFile::execute(asIScriptObject* object, asIScriptFunction* method, asIScriptContext* context,
  164. const std::vector<Variant>& parameters)
  165. {
  166. PROFILE(Script_ExecuteMethod);
  167. if ((!mCompiled) || (!object) || (!method))
  168. return false;
  169. if (!context)
  170. context = mScriptEngine->getImmediateContext();
  171. if (context->GetState() != asEXECUTION_ACTIVE)
  172. {
  173. if (context->Prepare(method->GetId()) < 0)
  174. return false;
  175. context->SetObject(object);
  176. setParameters(context, method, parameters);
  177. return context->Execute() >= 0;
  178. }
  179. else
  180. {
  181. // Prevent endless loop by nested script event handling
  182. if (executeNestingLevel > MAX_NESTING_LEVEL)
  183. {
  184. LOGERROR("Maximum script execution nesting level exceeded");
  185. return false;
  186. }
  187. // If context is active, allocate a temp context to allow nested execution.
  188. // This is not recommended for performance reasons
  189. LOGDEBUG("Executing " + std::string(method->GetDeclaration()) + " in a temporary script context");
  190. asIScriptContext* tempContext = mScriptEngine->createScriptContext();
  191. if (tempContext->Prepare(method->GetId()) < 0)
  192. {
  193. tempContext->Release();
  194. return false;
  195. }
  196. tempContext->SetObject(object);
  197. setParameters(tempContext, method, parameters);
  198. ++executeNestingLevel;
  199. bool success = tempContext->Execute() >= 0;
  200. tempContext->Release();
  201. --executeNestingLevel;
  202. return success;
  203. }
  204. }
  205. asIScriptObject* ScriptFile::createObject(const std::string& className, asIScriptContext* context)
  206. {
  207. PROFILE(Script_CreateObject);
  208. if (!isCompiled())
  209. return 0;
  210. if (!context)
  211. context = mScriptEngine->getImmediateContext();
  212. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  213. asIObjectType *type = engine->GetObjectTypeById(mScriptModule->GetTypeIdByDecl(className.c_str()));
  214. if (!type)
  215. return 0;
  216. // Get the factory function id from the object type
  217. std::string factoryName = className + "@ " + className + "()";
  218. int factoryId = type->GetFactoryIdByDecl(factoryName.c_str());
  219. if (factoryId < 0)
  220. return 0;
  221. if (context->Prepare(factoryId) < 0)
  222. return 0;
  223. if (context->Execute() < 0)
  224. return 0;
  225. asIScriptObject* obj = *(static_cast<asIScriptObject**>(context->GetAddressOfReturnValue()));
  226. if (obj)
  227. obj->AddRef();
  228. return obj;
  229. }
  230. asIScriptFunction* ScriptFile::getFunction(const std::string& declaration) const
  231. {
  232. if (!mCompiled)
  233. return 0;
  234. int id = mScriptModule->GetFunctionIdByDecl(declaration.c_str());
  235. return mScriptModule->GetFunctionDescriptorById(id);
  236. }
  237. asIScriptFunction* ScriptFile::getMethod(asIScriptObject* object, const std::string& declaration) const
  238. {
  239. if ((!mCompiled) || (!object))
  240. return 0;
  241. asIObjectType* type = object->GetObjectType();
  242. if (!type)
  243. return 0;
  244. int id = type->GetMethodIdByDecl(declaration.c_str());
  245. return mScriptModule->GetFunctionDescriptorById(id);
  246. }
  247. void ScriptFile::addScriptSection(asIScriptEngine* engine, Deserializer& source, ResourceCache* cache)
  248. {
  249. unsigned dataSize = source.getSize();
  250. SharedArrayPtr<char> buffer(new char[dataSize]);
  251. source.read((void*)buffer.getPtr(), dataSize);
  252. // Pre-parse for includes
  253. // Adapted from Angelscript's scriptbuilder add-on
  254. std::vector<std::string> includeFiles;
  255. unsigned pos = 0;
  256. while(pos < dataSize)
  257. {
  258. int len;
  259. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  260. if ((t == asTC_COMMENT) || (t == asTC_WHITESPACE))
  261. {
  262. pos += len;
  263. continue;
  264. }
  265. // Is this a preprocessor directive?
  266. if (buffer[pos] == '#')
  267. {
  268. int start = pos++;
  269. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  270. if (t == asTC_IDENTIFIER)
  271. {
  272. std::string token(&buffer[pos], len);
  273. if (token == "include")
  274. {
  275. pos += len;
  276. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  277. if (t == asTC_WHITESPACE)
  278. {
  279. pos += len;
  280. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  281. }
  282. if ((t == asTC_VALUE) && (len > 2) && (buffer[pos] == '"'))
  283. {
  284. // Get the include file
  285. std::string includeFile(&buffer[pos+1], len - 2);
  286. pos += len;
  287. // If the file is not found as it is, add the path of current file
  288. if (!cache->exists(includeFile))
  289. includeFile = getPath(getName()) + includeFile;
  290. std::string includeFileLower = toLower(includeFile);
  291. // If not included yet, store it for later processing
  292. if (mAllIncludeFiles.find(includeFileLower) == mAllIncludeFiles.end())
  293. {
  294. mAllIncludeFiles.insert(includeFileLower);
  295. includeFiles.push_back(includeFile);
  296. }
  297. // Overwrite the include directive with space characters to avoid compiler error
  298. memset(&buffer[start], ' ', pos - start);
  299. }
  300. }
  301. }
  302. }
  303. // Don't search includes within statement blocks or between tokens in statements
  304. else
  305. {
  306. int len;
  307. // Skip until ; or { whichever comes first
  308. while ((pos < dataSize) && (buffer[pos] != ';') && (buffer[pos] != '{' ))
  309. {
  310. engine->ParseToken(&buffer[pos], 0, &len);
  311. pos += len;
  312. }
  313. // Skip entire statement block
  314. if ((pos < dataSize) && (buffer[pos] == '{' ))
  315. {
  316. ++pos;
  317. // Find the end of the statement block
  318. int level = 1;
  319. while ((level > 0) && (pos < dataSize))
  320. {
  321. asETokenClass t = engine->ParseToken(&buffer[pos], 0, &len);
  322. if (t == asTC_KEYWORD)
  323. {
  324. if (buffer[pos] == '{')
  325. level++;
  326. else if(buffer[pos] == '}')
  327. level--;
  328. }
  329. pos += len;
  330. }
  331. }
  332. else
  333. ++pos;
  334. }
  335. }
  336. // Process includes first
  337. for (unsigned i = 0; i < includeFiles.size(); ++i)
  338. {
  339. SharedPtr<File> file = cache->getFile(includeFiles[i]);
  340. addScriptSection(engine, *file, cache);
  341. }
  342. // Then add this section
  343. if (mScriptModule->AddScriptSection(source.getName().c_str(), (const char*)buffer.getPtr(), dataSize) < 0)
  344. EXCEPTION("Failed to add script section " + source.getName());
  345. setMemoryUse(getMemoryUse() + dataSize);
  346. }
  347. void ScriptFile::setParameters(asIScriptContext* context, asIScriptFunction* function, const std::vector<Variant>& parameters)
  348. {
  349. unsigned paramCount = function->GetParamCount();
  350. for (unsigned i = 0; (i < parameters.size()) && (i < paramCount); ++i)
  351. {
  352. int paramType = function->GetParamTypeId(i);
  353. switch (paramType)
  354. {
  355. case asTYPEID_BOOL:
  356. context->SetArgByte(i, (unsigned char)parameters[i].getBool());
  357. break;
  358. case asTYPEID_INT8:
  359. case asTYPEID_UINT8:
  360. context->SetArgByte(i, parameters[i].getInt());
  361. break;
  362. case asTYPEID_INT16:
  363. case asTYPEID_UINT16:
  364. context->SetArgWord(i, parameters[i].getInt());
  365. break;
  366. case asTYPEID_INT32:
  367. case asTYPEID_UINT32:
  368. context->SetArgDWord(i, parameters[i].getInt());
  369. break;
  370. case asTYPEID_FLOAT:
  371. context->SetArgFloat(i, parameters[i].getFloat());
  372. break;
  373. default:
  374. if (paramType & asTYPEID_APPOBJECT)
  375. {
  376. switch (parameters[i].getType())
  377. {
  378. case VAR_VECTOR2:
  379. context->SetArgObject(i, (void *)&parameters[i].getVector2());
  380. break;
  381. case VAR_VECTOR3:
  382. context->SetArgObject(i, (void *)&parameters[i].getVector3());
  383. break;
  384. case VAR_VECTOR4:
  385. context->SetArgObject(i, (void *)&parameters[i].getVector4());
  386. break;
  387. case VAR_QUATERNION:
  388. context->SetArgObject(i, (void *)&parameters[i].getQuaternion());
  389. break;
  390. case VAR_STRING:
  391. context->SetArgObject(i, (void *)&parameters[i].getString());
  392. break;
  393. case VAR_PTR:
  394. context->SetArgObject(i, (void *)parameters[i].getPtr());
  395. break;
  396. }
  397. }
  398. break;
  399. }
  400. }
  401. }
  402. void ScriptFile::handleScriptEvent(StringHash eventType, VariantMap& eventData)
  403. {
  404. if (!mCompiled)
  405. return;
  406. std::map<StringHash, asIScriptFunction*>::iterator i = mEventHandlers.find(eventType);
  407. if (i == mEventHandlers.end())
  408. return;
  409. std::vector<Variant> parameters;
  410. parameters.push_back(Variant((void*)&eventType));
  411. parameters.push_back(Variant((void*)&eventData));
  412. execute(i->second, mScriptContext, parameters);
  413. }
  414. ScriptFile* getLastScriptFile()
  415. {
  416. return lastScriptFile;
  417. }