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. setParameters(context, function, parameters);
  124. return context->Execute() >= 0;
  125. }
  126. else
  127. {
  128. // Prevent endless loop by nested script event handling
  129. if (executeNestingLevel > MAX_NESTING_LEVEL)
  130. {
  131. LOGERROR("Maximum script execution nesting level exceeded");
  132. return false;
  133. }
  134. // If context is active, allocate a temp context to allow nested execution.
  135. // This is not recommended for performance reasons
  136. LOGDEBUG("Executing " + std::string(function->GetDeclaration()) + " in a temporary script context");
  137. asIScriptContext* tempContext = mScriptEngine->createScriptContext();
  138. tempContext->SetUserData(context->GetUserData());
  139. if (tempContext->Prepare(function->GetId()) < 0)
  140. {
  141. tempContext->Release();
  142. return false;
  143. }
  144. setParameters(tempContext, function, parameters);
  145. ++executeNestingLevel;
  146. bool success = tempContext->Execute() >= 0;
  147. tempContext->Release();
  148. --executeNestingLevel;
  149. return success;
  150. }
  151. }
  152. bool ScriptFile::execute(asIScriptObject* object, const std::string& declaration, asIScriptContext* context, const std::vector<Variant>& parameters)
  153. {
  154. asIScriptFunction* method = getMethod(object, declaration);
  155. if (!method)
  156. {
  157. LOGERROR("Method " + declaration + " not found in " + getName());
  158. return false;
  159. }
  160. return execute(object, method, context, parameters);
  161. }
  162. bool ScriptFile::execute(asIScriptObject* object, asIScriptFunction* method, asIScriptContext* context,
  163. const std::vector<Variant>& parameters)
  164. {
  165. PROFILE(Script_ExecuteMethod);
  166. if ((!mCompiled) || (!object) || (!method))
  167. return false;
  168. if (!context)
  169. context = mScriptEngine->getImmediateContext();
  170. if (context->GetState() != asEXECUTION_ACTIVE)
  171. {
  172. if (context->Prepare(method->GetId()) < 0)
  173. return false;
  174. context->SetObject(object);
  175. setParameters(context, method, parameters);
  176. return context->Execute() >= 0;
  177. }
  178. else
  179. {
  180. // Prevent endless loop by nested script event handling
  181. if (executeNestingLevel > MAX_NESTING_LEVEL)
  182. {
  183. LOGERROR("Maximum script execution nesting level exceeded");
  184. return false;
  185. }
  186. // If context is active, allocate a temp context to allow nested execution.
  187. // This is not recommended for performance reasons
  188. LOGDEBUG("Executing " + std::string(method->GetDeclaration()) + " in a temporary script context");
  189. asIScriptContext* tempContext = mScriptEngine->createScriptContext();
  190. tempContext->SetUserData(context->GetUserData());
  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. lastScriptFile = this;
  350. unsigned paramCount = function->GetParamCount();
  351. for (unsigned i = 0; (i < parameters.size()) && (i < paramCount); ++i)
  352. {
  353. int paramType = function->GetParamTypeId(i);
  354. switch (paramType)
  355. {
  356. case asTYPEID_BOOL:
  357. context->SetArgByte(i, (unsigned char)parameters[i].getBool());
  358. break;
  359. case asTYPEID_INT8:
  360. case asTYPEID_UINT8:
  361. context->SetArgByte(i, parameters[i].getInt());
  362. break;
  363. case asTYPEID_INT16:
  364. case asTYPEID_UINT16:
  365. context->SetArgWord(i, parameters[i].getInt());
  366. break;
  367. case asTYPEID_INT32:
  368. case asTYPEID_UINT32:
  369. context->SetArgDWord(i, parameters[i].getInt());
  370. break;
  371. case asTYPEID_FLOAT:
  372. context->SetArgFloat(i, parameters[i].getFloat());
  373. break;
  374. default:
  375. if (paramType & asTYPEID_APPOBJECT)
  376. {
  377. switch (parameters[i].getType())
  378. {
  379. case VAR_VECTOR2:
  380. context->SetArgObject(i, (void *)&parameters[i].getVector2());
  381. break;
  382. case VAR_VECTOR3:
  383. context->SetArgObject(i, (void *)&parameters[i].getVector3());
  384. break;
  385. case VAR_VECTOR4:
  386. context->SetArgObject(i, (void *)&parameters[i].getVector4());
  387. break;
  388. case VAR_QUATERNION:
  389. context->SetArgObject(i, (void *)&parameters[i].getQuaternion());
  390. break;
  391. case VAR_STRING:
  392. context->SetArgObject(i, (void *)&parameters[i].getString());
  393. break;
  394. case VAR_PTR:
  395. context->SetArgObject(i, (void *)parameters[i].getPtr());
  396. break;
  397. }
  398. }
  399. break;
  400. }
  401. }
  402. }
  403. void ScriptFile::handleScriptEvent(StringHash eventType, VariantMap& eventData)
  404. {
  405. if (!mCompiled)
  406. return;
  407. std::map<StringHash, asIScriptFunction*>::iterator i = mEventHandlers.find(eventType);
  408. if (i == mEventHandlers.end())
  409. return;
  410. std::vector<Variant> parameters;
  411. parameters.push_back(Variant((void*)&eventType));
  412. parameters.push_back(Variant((void*)&eventData));
  413. execute(i->second, mScriptContext, parameters);
  414. }
  415. ScriptFile* getLastScriptFile()
  416. {
  417. return lastScriptFile;
  418. }