Script.cpp 14 KB

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