Script.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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 "Addons.h"
  25. #include "Context.h"
  26. #include "Log.h"
  27. #include "Profiler.h"
  28. #include "Scene.h"
  29. #include "Script.h"
  30. #include "ScriptFile.h"
  31. #include "ScriptInstance.h"
  32. #include "StringUtils.h"
  33. #include <angelscript.h>
  34. #include "DebugNew.h"
  35. /// Script object property info for script API dump
  36. struct PropertyInfo
  37. {
  38. PropertyInfo() :
  39. read_(false),
  40. write_(false),
  41. indexed_(false)
  42. {
  43. }
  44. std::string name_;
  45. std::string type_;
  46. bool read_;
  47. bool write_;
  48. bool indexed_;
  49. };
  50. void ExtractPropertyInfo(const std::string& functionName, const std::string& declaration, std::vector<PropertyInfo>& propertyInfos)
  51. {
  52. std::string propertyName = functionName.substr(4);
  53. PropertyInfo* info = 0;
  54. for (unsigned k = 0; k < propertyInfos.size(); ++k)
  55. {
  56. if (propertyInfos[k].name_ == propertyName)
  57. info = &propertyInfos[k];
  58. }
  59. if (!info)
  60. {
  61. propertyInfos.resize(propertyInfos.size() + 1);
  62. info = &propertyInfos[propertyInfos.size() - 1];
  63. info->name_ = propertyName;
  64. }
  65. if (functionName.find("get_") != std::string::npos)
  66. {
  67. info->read_ = true;
  68. // Extract type from the return value
  69. std::vector<std::string> parts = Split(declaration, ' ');
  70. if (parts.size())
  71. {
  72. if (parts[0] != "const")
  73. info->type_ = parts[0];
  74. else if (parts.size() > 1)
  75. info->type_ = parts[1];
  76. }
  77. // If get method has parameters, it is indexed
  78. if (declaration.find("()") == std::string::npos)
  79. {
  80. info->indexed_ = true;
  81. info->type_ += "[]";
  82. }
  83. }
  84. if (functionName.find("set_") != std::string::npos)
  85. info->write_ = true;
  86. }
  87. OBJECTTYPESTATIC(Script);
  88. Script::Script(Context* context) :
  89. Object(context),
  90. scriptEngine_(0),
  91. immediateContext_(0),
  92. scriptNestingLevel_(0)
  93. {
  94. scriptEngine_ = asCreateScriptEngine(ANGELSCRIPT_VERSION);
  95. if (!scriptEngine_)
  96. {
  97. LOGERROR("Could not create AngelScript engine");
  98. return;
  99. }
  100. scriptEngine_->SetUserData(this);
  101. scriptEngine_->SetEngineProperty(asEP_USE_CHARACTER_LITERALS, true);
  102. scriptEngine_->SetEngineProperty(asEP_ALLOW_UNSAFE_REFERENCES, true);
  103. scriptEngine_->SetEngineProperty(asEP_ALLOW_IMPLICIT_HANDLE_TYPES, true);
  104. scriptEngine_->SetEngineProperty(asEP_BUILD_WITHOUT_LINE_CUES, true);
  105. scriptEngine_->SetMessageCallback(asMETHOD(Script, MessageCallback), this, asCALL_THISCALL);
  106. // Create the context for immediate execution
  107. immediateContext_ = scriptEngine_->CreateContext();
  108. immediateContext_->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  109. // Create the function/method contexts
  110. for (unsigned i = 0 ; i < MAX_SCRIPT_NESTING_LEVEL; ++i)
  111. {
  112. scriptFileContexts_.push_back(scriptEngine_->CreateContext());
  113. scriptFileContexts_[i]->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  114. }
  115. // Register the Array & String types
  116. RegisterArray(scriptEngine_);
  117. RegisterString(scriptEngine_);
  118. }
  119. Script::~Script()
  120. {
  121. if (immediateContext_)
  122. {
  123. immediateContext_->Release();
  124. immediateContext_ = 0;
  125. }
  126. for (unsigned i = 0 ; i < MAX_SCRIPT_NESTING_LEVEL; ++i)
  127. {
  128. if (scriptFileContexts_[i])
  129. scriptFileContexts_[i]->Release();
  130. }
  131. scriptFileContexts_.clear();
  132. if (scriptEngine_)
  133. {
  134. scriptEngine_->Release();
  135. scriptEngine_ = 0;
  136. }
  137. }
  138. bool Script::Execute(const std::string& line)
  139. {
  140. // Note: compiling code each time is slow. Not to be used for performance-critical or repeating activity
  141. PROFILE(ExecuteImmediate);
  142. std::string wrappedLine = "void f(){\n" + line + ";\n}";
  143. // If no immediate mode script file set, create a dummy module for compiling the line
  144. asIScriptModule* module = 0;
  145. if (defaultScriptFile_)
  146. module = defaultScriptFile_->GetScriptModule();
  147. if (!module)
  148. module = scriptEngine_->GetModule("ExecuteImmediate", asGM_CREATE_IF_NOT_EXISTS);
  149. if (!module)
  150. return false;
  151. asIScriptFunction *function = 0;
  152. if (module->CompileFunction("", wrappedLine.c_str(), -1, 0, &function) < 0)
  153. return false;
  154. if (immediateContext_->Prepare(function->GetId()) < 0)
  155. {
  156. function->Release();
  157. return false;
  158. }
  159. bool success = false;
  160. success = immediateContext_->Execute() >= 0;
  161. immediateContext_->Unprepare();
  162. function->Release();
  163. return success;
  164. }
  165. void Script::GarbageCollect(bool fullCycle)
  166. {
  167. PROFILE(GarbageCollect);
  168. if (fullCycle)
  169. scriptEngine_->GarbageCollect(asGC_FULL_CYCLE);
  170. else
  171. scriptEngine_->GarbageCollect(asGC_ONE_STEP);
  172. }
  173. void Script::SetDefaultScriptFile(ScriptFile* file)
  174. {
  175. defaultScriptFile_ = file;
  176. }
  177. void Script::SetDefaultScene(Scene* scene)
  178. {
  179. defaultScene_ = scene;
  180. }
  181. void Script::SetLogMode(ScriptLogMode mode)
  182. {
  183. logMode_ = mode;
  184. }
  185. void Script::ClearLogMessages()
  186. {
  187. logMessages_.clear();
  188. }
  189. void Script::DumpAPI()
  190. {
  191. LOGRAW("Urho3D script API:\n");
  192. std::vector<PropertyInfo> globalPropertyInfos;
  193. std::vector<std::string> globalFunctions;
  194. unsigned functions = scriptEngine_->GetGlobalFunctionCount();
  195. for (unsigned i = 0; i < functions; ++i)
  196. {
  197. unsigned id = scriptEngine_->GetGlobalFunctionIdByIndex(i);
  198. asIScriptFunction* function = scriptEngine_->GetFunctionDescriptorById(id);
  199. std::string functionName(function->GetName());
  200. std::string declaration(function->GetDeclaration());
  201. if ((functionName.find("set_") != std::string::npos) || (functionName.find("get_") != std::string::npos))
  202. ExtractPropertyInfo(functionName, declaration, globalPropertyInfos);
  203. else
  204. globalFunctions.push_back(declaration);
  205. }
  206. LOGRAW("\nGlobal functions:\n");
  207. for (unsigned i = 0; i < globalFunctions.size(); ++i)
  208. OutputAPIRow(globalFunctions[i]);
  209. LOGRAW("\nGlobal properties:\n");
  210. for (unsigned i = 0; i < globalPropertyInfos.size(); ++i)
  211. {
  212. // For now, skip write-only properties
  213. if (!globalPropertyInfos[i].read_)
  214. continue;
  215. OutputAPIRow(globalPropertyInfos[i].type_ + " " + globalPropertyInfos[i].name_, true);
  216. }
  217. LOGRAW("\nGlobal constants:\n");
  218. unsigned properties = scriptEngine_->GetGlobalPropertyCount();
  219. for (unsigned i = 0; i < properties; ++i)
  220. {
  221. const char* propertyName;
  222. const char* propertyDeclaration;
  223. int typeId;
  224. scriptEngine_->GetGlobalPropertyByIndex(i, &propertyName, &typeId);
  225. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  226. std::string type(propertyDeclaration);
  227. OutputAPIRow(type + " " + std::string(propertyName), true);
  228. }
  229. LOGRAW("\nClasses:\n");
  230. unsigned types = scriptEngine_->GetObjectTypeCount();
  231. for (unsigned i = 0; i < types; ++i)
  232. {
  233. asIObjectType* type = scriptEngine_->GetObjectTypeByIndex(i);
  234. if (type)
  235. {
  236. std::string typeName(type->GetName());
  237. std::vector<std::string> methodDeclarations;
  238. std::vector<PropertyInfo> propertyInfos;
  239. LOGRAW("\n" + typeName + "\n");
  240. unsigned methods = type->GetMethodCount();
  241. for (unsigned j = 0; j < methods; ++j)
  242. {
  243. asIScriptFunction* method = type->GetMethodDescriptorByIndex(j);
  244. std::string methodName(method->GetName());
  245. std::string declaration(method->GetDeclaration());
  246. if ((methodName.find("get_") == std::string::npos) && (methodName.find("set_") == std::string::npos))
  247. {
  248. // Sanitate the method name. For now, skip the operators
  249. if (declaration.find("::op") == std::string::npos)
  250. {
  251. std::string prefix(typeName + "::");
  252. ReplaceInPlace(declaration, prefix, "");
  253. methodDeclarations.push_back(declaration);
  254. }
  255. }
  256. else
  257. ExtractPropertyInfo(methodName, declaration, propertyInfos);
  258. }
  259. // Assume that the same property is never both an accessor property, and a direct one
  260. unsigned properties = type->GetPropertyCount();
  261. for (unsigned j = 0; j < properties; ++j)
  262. {
  263. const char* propertyName;
  264. const char* propertyDeclaration;
  265. int typeId;
  266. type->GetProperty(j, &propertyName, &typeId);
  267. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  268. PropertyInfo newInfo;
  269. newInfo.name_ = std::string(propertyName);
  270. newInfo.type_ = std::string(propertyDeclaration);
  271. newInfo.read_ = newInfo.write_ = true;
  272. propertyInfos.push_back(newInfo);
  273. }
  274. if (!methodDeclarations.empty())
  275. {
  276. LOGRAW("\nMethods:\n");
  277. for (unsigned j = 0; j < methodDeclarations.size(); ++j)
  278. OutputAPIRow(methodDeclarations[j]);
  279. }
  280. if (!propertyInfos.empty())
  281. {
  282. LOGRAW("\nProperties:\n");
  283. for (unsigned j = 0; j < propertyInfos.size(); ++j)
  284. {
  285. // For now, skip write-only properties
  286. if (!propertyInfos[j].read_)
  287. continue;
  288. std::string readOnly;
  289. if (!propertyInfos[j].write_)
  290. readOnly = " (readonly)";
  291. OutputAPIRow(propertyInfos[j].type_ + " " + propertyInfos[j].name_ + readOnly);
  292. }
  293. }
  294. LOGRAW("\n");
  295. }
  296. }
  297. }
  298. void Script::MessageCallback(const asSMessageInfo* msg)
  299. {
  300. std::string message = std::string(msg->section) + " (" + ToString(msg->row) + "," + ToString(msg->col) + ") " +
  301. std::string(msg->message);
  302. if (logMode_ == LOGMODE_IMMEDIATE)
  303. {
  304. switch (msg->type)
  305. {
  306. case asMSGTYPE_ERROR:
  307. LOGERROR(message);
  308. break;
  309. case asMSGTYPE_WARNING:
  310. LOGWARNING(message);
  311. break;
  312. default:
  313. LOGINFO(message);
  314. break;
  315. }
  316. }
  317. else
  318. {
  319. // Ignore info messages in retained mode
  320. if ((msg->type == asMSGTYPE_ERROR) || (msg->type == asMSGTYPE_WARNING))
  321. logMessages_ += message + "\n";
  322. }
  323. }
  324. void Script::ExceptionCallback(asIScriptContext* context)
  325. {
  326. int funcId = context->GetExceptionFunction();
  327. const asIScriptFunction *function = scriptEngine_->GetFunctionDescriptorById(funcId);
  328. std::string message = "Exception '" + std::string(context->GetExceptionString()) + "' in '" +
  329. std::string(function->GetDeclaration()) + "'";
  330. asSMessageInfo msg;
  331. msg.row = context->GetExceptionLineNumber(&msg.col, &msg.section);
  332. msg.type = asMSGTYPE_ERROR;
  333. msg.message = message.c_str();
  334. MessageCallback(&msg);
  335. }
  336. asIScriptContext* Script::GetScriptFileContext() const
  337. {
  338. return scriptNestingLevel_ < scriptFileContexts_.size() ? scriptFileContexts_[scriptNestingLevel_] : 0;
  339. }
  340. ScriptFile* Script::GetDefaultScriptFile() const
  341. {
  342. return defaultScriptFile_;
  343. }
  344. Scene* Script::GetDefaultScene() const
  345. {
  346. return defaultScene_;
  347. }
  348. asIObjectType* Script::GetObjectType(const char* declaration)
  349. {
  350. std::map<const char*, asIObjectType*>::const_iterator i = objectTypes_.find(declaration);
  351. if (i != objectTypes_.end())
  352. return i->second;
  353. asIObjectType* type = scriptEngine_->GetObjectTypeById(scriptEngine_->GetTypeIdByDecl(declaration));
  354. objectTypes_[declaration] = type;
  355. return type;
  356. }
  357. void Script::OutputAPIRow(const std::string& row, bool removeReference)
  358. {
  359. std::string out = row;
  360. ReplaceInPlace(out, "double", "float");
  361. ReplaceInPlace(out, "&in", "&");
  362. ReplaceInPlace(out, "&out", "&");
  363. if (removeReference)
  364. ReplaceInPlace(out, "&", "");
  365. LOGRAW(out + "\n");
  366. }
  367. void RegisterScriptLibrary(Context* context)
  368. {
  369. ScriptFile::RegisterObject(context);
  370. ScriptInstance::RegisterObject(context);
  371. }