Script.cpp 15 KB

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