ScriptFile.cpp 20 KB

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