ScriptFile.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 "Deserializer.h"
  25. #include "Log.h"
  26. #include "Profiler.h"
  27. #include "ScriptEngine.h"
  28. #include "ScriptFile.h"
  29. #include "SharedArrayPtr.h"
  30. #include <angelscript.h>
  31. #include "DebugNew.h"
  32. static const int MAX_NESTING_LEVEL = 100;
  33. static int executeNestingLevel = 0;
  34. ScriptFile::ScriptFile(ScriptEngine* scriptEngine, const std::string& name) :
  35. Resource(name),
  36. mScriptEngine(scriptEngine),
  37. mScriptModule(0),
  38. mCompiled(false)
  39. {
  40. if (!mScriptEngine)
  41. EXCEPTION("Null script engine");
  42. }
  43. ScriptFile::~ScriptFile()
  44. {
  45. if (mScriptModule)
  46. {
  47. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  48. engine->DiscardModule(getName().c_str());
  49. mScriptModule = 0;
  50. }
  51. }
  52. void ScriptFile::load(Deserializer& source, ResourceCache* cache)
  53. {
  54. PROFILE(Script_Load);
  55. unsigned dataSize = source.getSize();
  56. SharedArrayPtr<unsigned char> buffer(new unsigned char[dataSize]);
  57. source.read((void*)buffer.getPtr(), dataSize);
  58. // Discard the previous module if there was one
  59. setMemoryUse(0);
  60. mCompiled = false;
  61. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  62. mScriptModule = engine->GetModule(getName().c_str(), asGM_ALWAYS_CREATE);
  63. if (!mScriptModule)
  64. EXCEPTION("Failed to create script module " + getName());
  65. if (mScriptModule->AddScriptSection(getName().c_str(), (const char*)buffer.getPtr(), dataSize) < 0)
  66. EXCEPTION("Failed to add script section for script module " + getName());
  67. if (mScriptModule->Build() < 0)
  68. EXCEPTION("Failed to build script module " + getName());
  69. LOGINFO("Compiled script module " + getName());
  70. setMemoryUse(dataSize);
  71. mCompiled = true;
  72. }
  73. bool ScriptFile::execute(const std::string& declaration, asIScriptContext* context, const std::vector<Variant>& parameters)
  74. {
  75. asIScriptFunction* function = getFunction(declaration);
  76. if (!function)
  77. {
  78. LOGERROR("Function " + declaration + " not found in " + getName());
  79. return false;
  80. }
  81. return execute(getFunction(declaration), context, parameters);
  82. }
  83. bool ScriptFile::execute(asIScriptFunction* function, asIScriptContext* context, const std::vector<Variant>& parameters)
  84. {
  85. PROFILE(Script_Execute);
  86. if ((!mCompiled) || (!function))
  87. return false;
  88. if (!context)
  89. context = mScriptEngine->getImmediateContext();
  90. if (context->GetState() != asEXECUTION_ACTIVE)
  91. {
  92. if (context->Prepare(function->GetId()) < 0)
  93. return false;
  94. setParameters(context, function, parameters);
  95. return context->Execute() >= 0;
  96. }
  97. else
  98. {
  99. // Prevent endless loop by nested script event handling
  100. if (executeNestingLevel > MAX_NESTING_LEVEL)
  101. {
  102. LOGERROR("Maximum script execution nesting level exceeded");
  103. return false;
  104. }
  105. // If context is active, allocate a temp context to allow nested execution.
  106. // This is not recommended for performance reasons
  107. LOGDEBUG("Executing " + std::string(function->GetDeclaration()) + " in a temporary script context");
  108. asIScriptContext* tempContext = mScriptEngine->createScriptContext();
  109. tempContext->SetUserData(context->GetUserData());
  110. if (tempContext->Prepare(function->GetId()) < 0)
  111. {
  112. tempContext->Release();
  113. return false;
  114. }
  115. setParameters(tempContext, function, parameters);
  116. ++executeNestingLevel;
  117. bool success = tempContext->Execute() >= 0;
  118. tempContext->Release();
  119. --executeNestingLevel;
  120. return success;
  121. }
  122. }
  123. bool ScriptFile::execute(asIScriptObject* object, const std::string& declaration, asIScriptContext* context, const std::vector<Variant>& parameters)
  124. {
  125. asIScriptFunction* method = getMethod(object, declaration);
  126. if (!method)
  127. {
  128. LOGERROR("Method " + declaration + " not found in " + getName());
  129. return false;
  130. }
  131. return execute(object, method, context, parameters);
  132. }
  133. bool ScriptFile::execute(asIScriptObject* object, asIScriptFunction* method, asIScriptContext* context,
  134. const std::vector<Variant>& parameters)
  135. {
  136. PROFILE(Script_Execute);
  137. if ((!mCompiled) || (!object) || (!method))
  138. return false;
  139. if (!context)
  140. context = mScriptEngine->getImmediateContext();
  141. if (context->GetState() != asEXECUTION_ACTIVE)
  142. {
  143. if (context->Prepare(method->GetId()) < 0)
  144. return false;
  145. context->SetObject(object);
  146. setParameters(context, method, parameters);
  147. return context->Execute() >= 0;
  148. }
  149. else
  150. {
  151. // Prevent endless loop by nested script event handling
  152. if (executeNestingLevel > MAX_NESTING_LEVEL)
  153. {
  154. LOGERROR("Maximum script execution nesting level exceeded");
  155. return false;
  156. }
  157. // If context is active, allocate a temp context to allow nested execution.
  158. // This is not recommended for performance reasons
  159. LOGDEBUG("Executing " + std::string(method->GetDeclaration()) + " in a temporary script context");
  160. asIScriptContext* tempContext = mScriptEngine->createScriptContext();
  161. tempContext->SetUserData(context->GetUserData());
  162. if (tempContext->Prepare(method->GetId()) < 0)
  163. {
  164. tempContext->Release();
  165. return false;
  166. }
  167. tempContext->SetObject(object);
  168. setParameters(tempContext, method, parameters);
  169. ++executeNestingLevel;
  170. bool success = tempContext->Execute() >= 0;
  171. tempContext->Release();
  172. --executeNestingLevel;
  173. return success;
  174. }
  175. }
  176. asIScriptObject* ScriptFile::createObject(const std::string& className, asIScriptContext* context)
  177. {
  178. PROFILE(Script_CreateObject);
  179. if (!isCompiled())
  180. return 0;
  181. if (!context)
  182. context = mScriptEngine->getImmediateContext();
  183. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  184. asIObjectType *type = engine->GetObjectTypeById(mScriptModule->GetTypeIdByDecl(className.c_str()));
  185. if (!type)
  186. return 0;
  187. // Get the factory function id from the object type
  188. std::string factoryName = className + "@ " + className + "()";
  189. int factoryId = type->GetFactoryIdByDecl(factoryName.c_str());
  190. if (factoryId < 0)
  191. return 0;
  192. if (context->Prepare(factoryId) < 0)
  193. return 0;
  194. if (context->Execute() < 0)
  195. return 0;
  196. asIScriptObject* obj = *(static_cast<asIScriptObject**>(context->GetAddressOfReturnValue()));
  197. if (obj)
  198. obj->AddRef();
  199. return obj;
  200. }
  201. asIScriptFunction* ScriptFile::getFunction(const std::string& declaration) const
  202. {
  203. if (!mCompiled)
  204. return 0;
  205. int id = mScriptModule->GetFunctionIdByDecl(declaration.c_str());
  206. return mScriptModule->GetFunctionDescriptorById(id);
  207. }
  208. asIScriptFunction* ScriptFile::getMethod(asIScriptObject* object, const std::string& declaration) const
  209. {
  210. if ((!mCompiled) || (!object))
  211. return 0;
  212. asIObjectType* type = object->GetObjectType();
  213. if (!type)
  214. return 0;
  215. int id = type->GetMethodIdByDecl(declaration.c_str());
  216. return mScriptModule->GetFunctionDescriptorById(id);
  217. }
  218. void ScriptFile::setParameters(asIScriptContext* context, asIScriptFunction* function, const std::vector<Variant>& parameters)
  219. {
  220. unsigned paramCount = function->GetParamCount();
  221. for (unsigned i = 0; (i < parameters.size()) && (i < paramCount); ++i)
  222. {
  223. int paramType = function->GetParamTypeId(i);
  224. switch (paramType)
  225. {
  226. case asTYPEID_BOOL:
  227. context->SetArgByte(i, (unsigned char)parameters[i].getBool());
  228. break;
  229. case asTYPEID_INT8:
  230. case asTYPEID_UINT8:
  231. context->SetArgByte(i, parameters[i].getInt());
  232. break;
  233. case asTYPEID_INT16:
  234. case asTYPEID_UINT16:
  235. context->SetArgWord(i, parameters[i].getInt());
  236. break;
  237. case asTYPEID_INT32:
  238. case asTYPEID_UINT32:
  239. context->SetArgDWord(i, parameters[i].getInt());
  240. break;
  241. case asTYPEID_FLOAT:
  242. context->SetArgFloat(i, parameters[i].getFloat());
  243. break;
  244. default:
  245. if (paramType & asTYPEID_APPOBJECT)
  246. {
  247. switch (parameters[i].getType())
  248. {
  249. case VAR_VECTOR2:
  250. context->SetArgObject(i, (void *)&parameters[i].getVector2());
  251. break;
  252. case VAR_VECTOR3:
  253. context->SetArgObject(i, (void *)&parameters[i].getVector3());
  254. break;
  255. case VAR_VECTOR4:
  256. context->SetArgObject(i, (void *)&parameters[i].getVector4());
  257. break;
  258. case VAR_QUATERNION:
  259. context->SetArgObject(i, (void *)&parameters[i].getQuaternion());
  260. break;
  261. case VAR_STRING:
  262. context->SetArgObject(i, (void *)&parameters[i].getString());
  263. break;
  264. case VAR_PTR:
  265. context->SetArgObject(i, (void *)parameters[i].getPtr());
  266. break;
  267. }
  268. }
  269. break;
  270. }
  271. }
  272. }