Script.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. // Register the Array & String types
  141. RegisterArray(scriptEngine_);
  142. RegisterString(scriptEngine_);
  143. }
  144. Script::~Script()
  145. {
  146. if (immediateContext_)
  147. {
  148. immediateContext_->Release();
  149. immediateContext_ = 0;
  150. }
  151. for (unsigned i = 0 ; i < scriptFileContexts_.Size(); ++i)
  152. scriptFileContexts_[i]->Release();
  153. scriptFileContexts_.Clear();
  154. if (scriptEngine_)
  155. {
  156. scriptEngine_->Release();
  157. scriptEngine_ = 0;
  158. }
  159. }
  160. bool Script::Execute(const String& line)
  161. {
  162. // Note: compiling code each time is slow. Not to be used for performance-critical or repeating activity
  163. PROFILE(ExecuteImmediate);
  164. ClearObjectTypeCache();
  165. String wrappedLine = "void f(){\n" + line + ";\n}";
  166. // If no immediate mode script file set, create a dummy module for compiling the line
  167. asIScriptModule* module = 0;
  168. if (defaultScriptFile_)
  169. module = defaultScriptFile_->GetScriptModule();
  170. if (!module)
  171. module = scriptEngine_->GetModule("ExecuteImmediate", asGM_CREATE_IF_NOT_EXISTS);
  172. if (!module)
  173. return false;
  174. asIScriptFunction *function = 0;
  175. if (module->CompileFunction("", wrappedLine.CString(), -1, 0, &function) < 0)
  176. return false;
  177. if (immediateContext_->Prepare(function) < 0)
  178. {
  179. function->Release();
  180. return false;
  181. }
  182. bool success = false;
  183. success = immediateContext_->Execute() >= 0;
  184. immediateContext_->Unprepare();
  185. function->Release();
  186. return success;
  187. }
  188. void Script::SetDefaultScriptFile(ScriptFile* file)
  189. {
  190. defaultScriptFile_ = file;
  191. }
  192. void Script::SetDefaultScene(Scene* scene)
  193. {
  194. defaultScene_ = scene;
  195. }
  196. void Script::SetLogMode(ScriptLogMode mode)
  197. {
  198. logMode_ = mode;
  199. }
  200. void Script::ClearLogMessages()
  201. {
  202. logMessages_.Clear();
  203. }
  204. void Script::DumpAPI()
  205. {
  206. LOGRAW("/**\n\\page ScriptAPI Scripting API \n\n");
  207. Vector<PropertyInfo> globalPropertyInfos;
  208. Vector<String> globalFunctions;
  209. unsigned functions = scriptEngine_->GetGlobalFunctionCount();
  210. for (unsigned i = 0; i < functions; ++i)
  211. {
  212. asIScriptFunction* function = scriptEngine_->GetGlobalFunctionByIndex(i);
  213. String functionName(function->GetName());
  214. String declaration(function->GetDeclaration());
  215. if (functionName.Find("set_") != String::NPOS || functionName.Find("get_") != String::NPOS)
  216. ExtractPropertyInfo(functionName, declaration, globalPropertyInfos);
  217. else
  218. globalFunctions.Push(declaration);
  219. }
  220. LOGRAW("\\section ScriptAPI_GlobalFunctions Global functions\n");
  221. for (unsigned i = 0; i < globalFunctions.Size(); ++i)
  222. OutputAPIRow(globalFunctions[i]);
  223. LOGRAW("\\section ScriptAPI_GlobalProperties Global properties\n");
  224. for (unsigned i = 0; i < globalPropertyInfos.Size(); ++i)
  225. OutputAPIRow(globalPropertyInfos[i].type_ + " " + globalPropertyInfos[i].name_, true);
  226. LOGRAW("\\section ScriptAPI_GlobalConstants Global constants\n");
  227. unsigned properties = scriptEngine_->GetGlobalPropertyCount();
  228. for (unsigned i = 0; i < properties; ++i)
  229. {
  230. const char* propertyName;
  231. const char* propertyDeclaration;
  232. int typeId;
  233. scriptEngine_->GetGlobalPropertyByIndex(i, &propertyName, 0, &typeId);
  234. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  235. String type(propertyDeclaration);
  236. OutputAPIRow(type + " " + String(propertyName), true);
  237. }
  238. LOGRAW("\\section ScriptAPI_Classes Classes\n");
  239. unsigned types = scriptEngine_->GetObjectTypeCount();
  240. for (unsigned i = 0; i < types; ++i)
  241. {
  242. asIObjectType* type = scriptEngine_->GetObjectTypeByIndex(i);
  243. if (type)
  244. {
  245. String typeName(type->GetName());
  246. Vector<String> methodDeclarations;
  247. Vector<PropertyInfo> propertyInfos;
  248. LOGRAW("\n" + typeName + "\n");
  249. unsigned methods = type->GetMethodCount();
  250. for (unsigned j = 0; j < methods; ++j)
  251. {
  252. asIScriptFunction* method = type->GetMethodByIndex(j);
  253. String methodName(method->GetName());
  254. String declaration(method->GetDeclaration());
  255. if (methodName.Find("get_") == String::NPOS && methodName.Find("set_") == String::NPOS)
  256. {
  257. // Sanitate the method name. For now, skip the operators
  258. if (declaration.Find("::op") == String::NPOS)
  259. {
  260. String prefix(typeName + "::");
  261. declaration.Replace(prefix, "");
  262. methodDeclarations.Push(declaration);
  263. }
  264. }
  265. else
  266. ExtractPropertyInfo(methodName, declaration, propertyInfos);
  267. }
  268. // Assume that the same property is never both an accessor property, and a direct one
  269. unsigned properties = type->GetPropertyCount();
  270. for (unsigned j = 0; j < properties; ++j)
  271. {
  272. const char* propertyName;
  273. const char* propertyDeclaration;
  274. int typeId;
  275. type->GetProperty(j, &propertyName, &typeId);
  276. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  277. PropertyInfo newInfo;
  278. newInfo.name_ = String(propertyName);
  279. newInfo.type_ = String(propertyDeclaration);
  280. newInfo.read_ = newInfo.write_ = true;
  281. propertyInfos.Push(newInfo);
  282. }
  283. if (!methodDeclarations.Empty())
  284. {
  285. LOGRAW("\nMethods:<br>\n");
  286. for (unsigned j = 0; j < methodDeclarations.Size(); ++j)
  287. OutputAPIRow(methodDeclarations[j]);
  288. }
  289. if (!propertyInfos.Empty())
  290. {
  291. LOGRAW("\nProperties:<br>\n");
  292. for (unsigned j = 0; j < propertyInfos.Size(); ++j)
  293. {
  294. String remark;
  295. if (!propertyInfos[j].write_)
  296. remark = " (readonly)";
  297. else if (!propertyInfos[j].read_)
  298. remark = " (writeonly)";
  299. OutputAPIRow(propertyInfos[j].type_ + " " + propertyInfos[j].name_ + remark);
  300. }
  301. }
  302. LOGRAW("\n");
  303. }
  304. }
  305. LOGRAW("*/\n");
  306. }
  307. void Script::MessageCallback(const asSMessageInfo* msg)
  308. {
  309. String message = String(msg->section) + " (" + String(msg->row) + "," + String(msg->col) + ") " +
  310. String(msg->message);
  311. if (logMode_ == LOGMODE_IMMEDIATE)
  312. {
  313. switch (msg->type)
  314. {
  315. case asMSGTYPE_ERROR:
  316. LOGERROR(message);
  317. break;
  318. case asMSGTYPE_WARNING:
  319. LOGWARNING(message);
  320. break;
  321. default:
  322. LOGINFO(message);
  323. break;
  324. }
  325. }
  326. else
  327. {
  328. // Ignore info messages in retained mode
  329. if (msg->type == asMSGTYPE_ERROR || msg->type == asMSGTYPE_WARNING)
  330. logMessages_ += message + "\n";
  331. }
  332. }
  333. void Script::ExceptionCallback(asIScriptContext* context)
  334. {
  335. asIScriptFunction *function = context->GetExceptionFunction();
  336. String message = "Exception '" + String(context->GetExceptionString()) + "' in '" +
  337. String(function->GetDeclaration()) + "'";
  338. asSMessageInfo msg;
  339. msg.row = context->GetExceptionLineNumber(&msg.col, &msg.section);
  340. msg.type = asMSGTYPE_ERROR;
  341. msg.message = message.CString();
  342. MessageCallback(&msg);
  343. }
  344. ScriptFile* Script::GetDefaultScriptFile() const
  345. {
  346. return defaultScriptFile_;
  347. }
  348. Scene* Script::GetDefaultScene() const
  349. {
  350. return defaultScene_;
  351. }
  352. void Script::ClearObjectTypeCache()
  353. {
  354. objectTypes_.Clear();
  355. }
  356. asIObjectType* Script::GetObjectType(const char* declaration)
  357. {
  358. Map<const char*, asIObjectType*>::ConstIterator i = objectTypes_.Find(declaration);
  359. if (i != objectTypes_.End())
  360. return i->second_;
  361. asIObjectType* type = scriptEngine_->GetObjectTypeById(scriptEngine_->GetTypeIdByDecl(declaration));
  362. objectTypes_[declaration] = type;
  363. return type;
  364. }
  365. asIScriptContext* Script::GetScriptFileContext()
  366. {
  367. while (scriptNestingLevel_ >= scriptFileContexts_.Size())
  368. {
  369. asIScriptContext* newContext = scriptEngine_->CreateContext();
  370. newContext->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  371. scriptFileContexts_.Push(newContext);
  372. }
  373. return scriptFileContexts_[scriptNestingLevel_];
  374. }
  375. void Script::OutputAPIRow(const String& row, bool removeReference)
  376. {
  377. String out = row;
  378. out.Replace("double", "float");
  379. out.Replace("&in", "&");
  380. out.Replace("&out", "&");
  381. if (removeReference)
  382. out.Replace("&", "");
  383. LOGRAW("- " + out + "\n");
  384. }
  385. void RegisterScriptLibrary(Context* context)
  386. {
  387. ScriptFile::RegisterObject(context);
  388. ScriptInstance::RegisterObject(context);
  389. }