Script.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. String name_;
  45. String type_;
  46. bool read_;
  47. bool write_;
  48. bool indexed_;
  49. };
  50. void ExtractPropertyInfo(const String& functionName, const String& declaration, Vector<PropertyInfo>& propertyInfos)
  51. {
  52. String propertyName = functionName.Substring(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_") != String::NPOS)
  66. {
  67. info->read_ = true;
  68. // Extract type from the return value
  69. Vector<String> parts = declaration.Split(' ');
  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("()") == String::NPOS)
  79. {
  80. info->indexed_ = true;
  81. info->type_ += "[]";
  82. }
  83. }
  84. if (functionName.Find("set_") != 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(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 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. 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.CString(), -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. Vector<PropertyInfo> globalPropertyInfos;
  193. Vector<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. String functionName(function->GetName());
  200. String declaration(function->GetDeclaration());
  201. if ((functionName.Find("set_") != String::NPOS) || (functionName.Find("get_") != String::NPOS))
  202. ExtractPropertyInfo(functionName, declaration, globalPropertyInfos);
  203. else
  204. globalFunctions.Push(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. String type(propertyDeclaration);
  227. OutputAPIRow(type + " " + 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. String typeName(type->GetName());
  237. Vector<String> methodDeclarations;
  238. 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. String methodName(method->GetName());
  245. String declaration(method->GetDeclaration());
  246. if ((methodName.Find("get_") == String::NPOS) && (methodName.Find("set_") == String::NPOS))
  247. {
  248. // Sanitate the method name. For now, skip the operators
  249. if (declaration.Find("::op") == String::NPOS)
  250. {
  251. String prefix(typeName + "::");
  252. methodDeclarations.Push(declaration.Replace(prefix, ""));
  253. }
  254. }
  255. else
  256. ExtractPropertyInfo(methodName, declaration, propertyInfos);
  257. }
  258. // Assume that the same property is never both an accessor property, and a direct one
  259. unsigned properties = type->GetPropertyCount();
  260. for (unsigned j = 0; j < properties; ++j)
  261. {
  262. const char* propertyName;
  263. const char* propertyDeclaration;
  264. int typeId;
  265. type->GetProperty(j, &propertyName, &typeId);
  266. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  267. PropertyInfo newInfo;
  268. newInfo.name_ = String(propertyName);
  269. newInfo.type_ = String(propertyDeclaration);
  270. newInfo.read_ = newInfo.write_ = true;
  271. propertyInfos.Push(newInfo);
  272. }
  273. if (!methodDeclarations.Empty())
  274. {
  275. LOGRAW("\nMethods:\n");
  276. for (unsigned j = 0; j < methodDeclarations.Size(); ++j)
  277. OutputAPIRow(methodDeclarations[j]);
  278. }
  279. if (!propertyInfos.Empty())
  280. {
  281. LOGRAW("\nProperties:\n");
  282. for (unsigned j = 0; j < propertyInfos.Size(); ++j)
  283. {
  284. // For now, skip write-only properties
  285. if (!propertyInfos[j].read_)
  286. continue;
  287. String readOnly;
  288. if (!propertyInfos[j].write_)
  289. readOnly = " (readonly)";
  290. OutputAPIRow(propertyInfos[j].type_ + " " + propertyInfos[j].name_ + readOnly);
  291. }
  292. }
  293. LOGRAW("\n");
  294. }
  295. }
  296. }
  297. void Script::MessageCallback(const asSMessageInfo* msg)
  298. {
  299. String message = String(msg->section) + " (" + msg->row + "," + msg->col + ") " +
  300. String(msg->message);
  301. if (logMode_ == LOGMODE_IMMEDIATE)
  302. {
  303. switch (msg->type)
  304. {
  305. case asMSGTYPE_ERROR:
  306. LOGERROR(message);
  307. break;
  308. case asMSGTYPE_WARNING:
  309. LOGWARNING(message);
  310. break;
  311. default:
  312. LOGINFO(message);
  313. break;
  314. }
  315. }
  316. else
  317. {
  318. // Ignore info messages in retained mode
  319. if ((msg->type == asMSGTYPE_ERROR) || (msg->type == asMSGTYPE_WARNING))
  320. logMessages_ += message + "\n";
  321. }
  322. }
  323. void Script::ExceptionCallback(asIScriptContext* context)
  324. {
  325. int funcId = context->GetExceptionFunction();
  326. const asIScriptFunction *function = scriptEngine_->GetFunctionDescriptorById(funcId);
  327. String message = "Exception '" + String(context->GetExceptionString()) + "' in '" +
  328. String(function->GetDeclaration()) + "'";
  329. asSMessageInfo msg;
  330. msg.row = context->GetExceptionLineNumber(&msg.col, &msg.section);
  331. msg.type = asMSGTYPE_ERROR;
  332. msg.message = message.CString();
  333. MessageCallback(&msg);
  334. }
  335. asIScriptContext* Script::GetScriptFileContext() const
  336. {
  337. return scriptNestingLevel_ < scriptFileContexts_.Size() ? scriptFileContexts_[scriptNestingLevel_] : 0;
  338. }
  339. ScriptFile* Script::GetDefaultScriptFile() const
  340. {
  341. return defaultScriptFile_;
  342. }
  343. Scene* Script::GetDefaultScene() const
  344. {
  345. return defaultScene_;
  346. }
  347. asIObjectType* Script::GetObjectType(const char* declaration)
  348. {
  349. Map<const char*, asIObjectType*>::ConstIterator i = objectTypes_.Find(declaration);
  350. if (i != objectTypes_.End())
  351. return i->second_;
  352. asIObjectType* type = scriptEngine_->GetObjectTypeById(scriptEngine_->GetTypeIdByDecl(declaration));
  353. objectTypes_[declaration] = type;
  354. return type;
  355. }
  356. void Script::OutputAPIRow(const String& row, bool removeReference)
  357. {
  358. String out = row;
  359. out.ReplaceInPlace("double", "float");
  360. out.ReplaceInPlace("&in", "&");
  361. out.ReplaceInPlace("&out", "&");
  362. if (removeReference)
  363. out.ReplaceInPlace("&", "");
  364. LOGRAW(out + "\n");
  365. }
  366. void RegisterScriptLibrary(Context* context)
  367. {
  368. ScriptFile::RegisterObject(context);
  369. ScriptInstance::RegisterObject(context);
  370. }