Script.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Addons.h"
  24. #include "Context.h"
  25. #include "EngineEvents.h"
  26. #include "Log.h"
  27. #include "Profiler.h"
  28. #include "Scene.h"
  29. #include "Script.h"
  30. #include "ScriptAPI.h"
  31. #include "ScriptFile.h"
  32. #include "ScriptInstance.h"
  33. #include <angelscript.h>
  34. #include "DebugNew.h"
  35. namespace Urho3D
  36. {
  37. /// %Object property info for scripting API dump.
  38. struct PropertyInfo
  39. {
  40. /// Construct.
  41. PropertyInfo() :
  42. read_(false),
  43. write_(false),
  44. indexed_(false)
  45. {
  46. }
  47. /// Property name.
  48. String name_;
  49. /// Property data type.
  50. String type_;
  51. /// Reading supported flag.
  52. bool read_;
  53. /// Writing supported flag.
  54. bool write_;
  55. /// Indexed flag.
  56. bool indexed_;
  57. };
  58. void ExtractPropertyInfo(const String& functionName, const String& declaration, Vector<PropertyInfo>& propertyInfos)
  59. {
  60. String propertyName = functionName.Substring(4);
  61. PropertyInfo* info = 0;
  62. for (unsigned k = 0; k < propertyInfos.Size(); ++k)
  63. {
  64. if (propertyInfos[k].name_ == propertyName)
  65. {
  66. info = &propertyInfos[k];
  67. break;
  68. }
  69. }
  70. if (!info)
  71. {
  72. propertyInfos.Resize(propertyInfos.Size() + 1);
  73. info = &propertyInfos.Back();
  74. info->name_ = propertyName;
  75. }
  76. if (functionName.Contains("get_"))
  77. {
  78. info->read_ = true;
  79. // Extract type from the return value
  80. Vector<String> parts = declaration.Split(' ');
  81. if (parts.Size())
  82. {
  83. if (parts[0] != "const")
  84. info->type_ = parts[0];
  85. else if (parts.Size() > 1)
  86. info->type_ = parts[1];
  87. }
  88. // If get method has parameters, it is indexed
  89. if (!declaration.Contains("()"))
  90. {
  91. info->indexed_ = true;
  92. info->type_ += "[]";
  93. }
  94. // Sanitate the reference operator away
  95. info->type_.Replace("&", "");
  96. }
  97. if (functionName.Contains("set_"))
  98. {
  99. info->write_ = true;
  100. if (info->type_.Empty())
  101. {
  102. // Extract type from parameters
  103. unsigned begin = declaration.Find(',');
  104. if (begin == String::NPOS)
  105. begin = declaration.Find('(');
  106. else
  107. info->indexed_ = true;
  108. if (begin != String::NPOS)
  109. {
  110. ++begin;
  111. unsigned end = declaration.Find(')');
  112. if (end != String::NPOS)
  113. {
  114. info->type_ = declaration.Substring(begin, end - begin);
  115. // Sanitate const & reference operator away
  116. info->type_.Replace("const ", "");
  117. info->type_.Replace("&in", "");
  118. info->type_.Replace("&", "");
  119. }
  120. }
  121. }
  122. }
  123. }
  124. Script::Script(Context* context) :
  125. Object(context),
  126. scriptEngine_(0),
  127. immediateContext_(0),
  128. logMode_(LOGMODE_IMMEDIATE),
  129. scriptNestingLevel_(0)
  130. {
  131. scriptEngine_ = asCreateScriptEngine(ANGELSCRIPT_VERSION);
  132. if (!scriptEngine_)
  133. {
  134. LOGERROR("Could not create AngelScript engine");
  135. return;
  136. }
  137. scriptEngine_->SetUserData(this);
  138. scriptEngine_->SetEngineProperty(asEP_USE_CHARACTER_LITERALS, true);
  139. scriptEngine_->SetEngineProperty(asEP_ALLOW_UNSAFE_REFERENCES, true);
  140. scriptEngine_->SetEngineProperty(asEP_ALLOW_IMPLICIT_HANDLE_TYPES, true);
  141. scriptEngine_->SetEngineProperty(asEP_BUILD_WITHOUT_LINE_CUES, true);
  142. scriptEngine_->SetMessageCallback(asMETHOD(Script, MessageCallback), this, asCALL_THISCALL);
  143. // Create the context for immediate execution
  144. immediateContext_ = scriptEngine_->CreateContext();
  145. immediateContext_->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  146. // Register Script library object factories
  147. RegisterScriptLibrary(context_);
  148. // Register the Array & String API
  149. RegisterArray(scriptEngine_);
  150. RegisterString(scriptEngine_);
  151. // Register the rest of the script API
  152. RegisterMathAPI(scriptEngine_);
  153. RegisterCoreAPI(scriptEngine_);
  154. RegisterIOAPI(scriptEngine_);
  155. RegisterResourceAPI(scriptEngine_);
  156. RegisterSceneAPI(scriptEngine_);
  157. RegisterGraphicsAPI(scriptEngine_);
  158. RegisterInputAPI(scriptEngine_);
  159. RegisterAudioAPI(scriptEngine_);
  160. RegisterUIAPI(scriptEngine_);
  161. RegisterNetworkAPI(scriptEngine_);
  162. RegisterPhysicsAPI(scriptEngine_);
  163. RegisterNavigationAPI(scriptEngine_);
  164. RegisterScriptAPI(scriptEngine_);
  165. RegisterEngineAPI(scriptEngine_);
  166. // Subscribe to console commands
  167. SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(Script, HandleConsoleCommand));
  168. }
  169. Script::~Script()
  170. {
  171. if (immediateContext_)
  172. {
  173. immediateContext_->Release();
  174. immediateContext_ = 0;
  175. }
  176. for (unsigned i = 0 ; i < scriptFileContexts_.Size(); ++i)
  177. scriptFileContexts_[i]->Release();
  178. if (scriptEngine_)
  179. {
  180. scriptEngine_->Release();
  181. scriptEngine_ = 0;
  182. }
  183. }
  184. bool Script::Execute(const String& line)
  185. {
  186. // Note: compiling code each time is slow. Not to be used for performance-critical or repeating activity
  187. PROFILE(ExecuteImmediate);
  188. ClearObjectTypeCache();
  189. String wrappedLine = "void f(){\n" + line + ";\n}";
  190. // If no immediate mode script file set, create a dummy module for compiling the line
  191. asIScriptModule* module = 0;
  192. if (defaultScriptFile_)
  193. module = defaultScriptFile_->GetScriptModule();
  194. if (!module)
  195. module = scriptEngine_->GetModule("ExecuteImmediate", asGM_CREATE_IF_NOT_EXISTS);
  196. if (!module)
  197. return false;
  198. asIScriptFunction *function = 0;
  199. if (module->CompileFunction("", wrappedLine.CString(), -1, 0, &function) < 0)
  200. return false;
  201. if (immediateContext_->Prepare(function) < 0)
  202. {
  203. function->Release();
  204. return false;
  205. }
  206. bool success = immediateContext_->Execute() >= 0;
  207. immediateContext_->Unprepare();
  208. function->Release();
  209. return success;
  210. }
  211. void Script::SetDefaultScriptFile(ScriptFile* file)
  212. {
  213. defaultScriptFile_ = file;
  214. }
  215. void Script::SetDefaultScene(Scene* scene)
  216. {
  217. defaultScene_ = scene;
  218. }
  219. void Script::SetLogMode(ScriptLogMode mode)
  220. {
  221. logMode_ = mode;
  222. }
  223. void Script::ClearLogMessages()
  224. {
  225. logMessages_.Clear();
  226. }
  227. void Script::DumpAPI()
  228. {
  229. // Does not use LOGRAW macro here to ensure the messages are always dumped regarless of ENABLE_LOGGING compiler directive and of Log subsystem availability
  230. Log::WriteRaw("namespace Urho3D\n{\n\n/**\n\\page ScriptAPI Scripting API\n\n");
  231. Vector<PropertyInfo> globalPropertyInfos;
  232. Vector<String> globalFunctions;
  233. unsigned functions = scriptEngine_->GetGlobalFunctionCount();
  234. for (unsigned i = 0; i < functions; ++i)
  235. {
  236. asIScriptFunction* function = scriptEngine_->GetGlobalFunctionByIndex(i);
  237. String functionName(function->GetName());
  238. String declaration(function->GetDeclaration());
  239. if (functionName.Contains("set_") || functionName.Contains("get_"))
  240. ExtractPropertyInfo(functionName, declaration, globalPropertyInfos);
  241. else
  242. globalFunctions.Push(declaration);
  243. }
  244. Log::WriteRaw("\\section ScriptAPI_GlobalFunctions Global functions\n");
  245. for (unsigned i = 0; i < globalFunctions.Size(); ++i)
  246. OutputAPIRow(globalFunctions[i]);
  247. Log::WriteRaw("\\section ScriptAPI_GlobalProperties Global properties\n");
  248. for (unsigned i = 0; i < globalPropertyInfos.Size(); ++i)
  249. OutputAPIRow(globalPropertyInfos[i].type_ + " " + globalPropertyInfos[i].name_, true);
  250. Log::WriteRaw("\\section ScriptAPI_GlobalConstants Global constants\n");
  251. unsigned properties = scriptEngine_->GetGlobalPropertyCount();
  252. for (unsigned i = 0; i < properties; ++i)
  253. {
  254. const char* propertyName;
  255. const char* propertyDeclaration;
  256. int typeId;
  257. scriptEngine_->GetGlobalPropertyByIndex(i, &propertyName, 0, &typeId);
  258. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  259. String type(propertyDeclaration);
  260. OutputAPIRow(type + " " + String(propertyName), true);
  261. }
  262. Log::WriteRaw("\\section ScriptAPI_Classes Classes\n");
  263. unsigned types = scriptEngine_->GetObjectTypeCount();
  264. for (unsigned i = 0; i < types; ++i)
  265. {
  266. asIObjectType* type = scriptEngine_->GetObjectTypeByIndex(i);
  267. if (type)
  268. {
  269. String typeName(type->GetName());
  270. Vector<String> methodDeclarations;
  271. Vector<PropertyInfo> propertyInfos;
  272. Log::WriteRaw("\n" + typeName + "\n");
  273. unsigned methods = type->GetMethodCount();
  274. for (unsigned j = 0; j < methods; ++j)
  275. {
  276. asIScriptFunction* method = type->GetMethodByIndex(j);
  277. String methodName(method->GetName());
  278. String declaration(method->GetDeclaration());
  279. if (methodName.Contains("get_") || methodName.Contains("set_"))
  280. ExtractPropertyInfo(methodName, declaration, propertyInfos);
  281. else
  282. {
  283. // Sanitate the method name. \todo For now, skip the operators
  284. if (!declaration.Contains("::op"))
  285. {
  286. String prefix(typeName + "::");
  287. declaration.Replace(prefix, "");
  288. methodDeclarations.Push(declaration);
  289. }
  290. }
  291. }
  292. // Assume that the same property is never both an accessor property, and a direct one
  293. unsigned properties = type->GetPropertyCount();
  294. for (unsigned j = 0; j < properties; ++j)
  295. {
  296. const char* propertyName;
  297. const char* propertyDeclaration;
  298. int typeId;
  299. type->GetProperty(j, &propertyName, &typeId);
  300. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  301. PropertyInfo newInfo;
  302. newInfo.name_ = String(propertyName);
  303. newInfo.type_ = String(propertyDeclaration);
  304. newInfo.read_ = newInfo.write_ = true;
  305. propertyInfos.Push(newInfo);
  306. }
  307. if (!methodDeclarations.Empty())
  308. {
  309. Log::WriteRaw("\nMethods:<br>\n");
  310. for (unsigned j = 0; j < methodDeclarations.Size(); ++j)
  311. OutputAPIRow(methodDeclarations[j]);
  312. }
  313. if (!propertyInfos.Empty())
  314. {
  315. Log::WriteRaw("\nProperties:<br>\n");
  316. for (unsigned j = 0; j < propertyInfos.Size(); ++j)
  317. {
  318. String remark;
  319. if (!propertyInfos[j].write_)
  320. remark = " (readonly)";
  321. else if (!propertyInfos[j].read_)
  322. remark = " (writeonly)";
  323. OutputAPIRow(propertyInfos[j].type_ + " " + propertyInfos[j].name_ + remark);
  324. }
  325. }
  326. Log::WriteRaw("\n");
  327. }
  328. }
  329. Log::WriteRaw("*/\n\n}\n");
  330. }
  331. void Script::MessageCallback(const asSMessageInfo* msg)
  332. {
  333. String message;
  334. message.AppendWithFormat("%s:%d,%d %s", msg->section, msg->row, msg->col, msg->message);
  335. if (logMode_ == LOGMODE_IMMEDIATE)
  336. {
  337. switch (msg->type)
  338. {
  339. case asMSGTYPE_ERROR:
  340. LOGERROR(message);
  341. break;
  342. case asMSGTYPE_WARNING:
  343. LOGWARNING(message);
  344. break;
  345. default:
  346. LOGINFO(message);
  347. break;
  348. }
  349. }
  350. else
  351. {
  352. // Ignore info messages in retained mode
  353. if (msg->type == asMSGTYPE_ERROR || msg->type == asMSGTYPE_WARNING)
  354. logMessages_ += message + "\n";
  355. }
  356. }
  357. void Script::ExceptionCallback(asIScriptContext* context)
  358. {
  359. String message;
  360. message.AppendWithFormat("- Exception '%s' in '%s'\n%s", context->GetExceptionString(), context->GetExceptionFunction()->GetDeclaration(), GetCallStack(context).CString());
  361. asSMessageInfo msg;
  362. msg.row = context->GetExceptionLineNumber(&msg.col, &msg.section);
  363. msg.type = asMSGTYPE_ERROR;
  364. msg.message = message.CString();
  365. MessageCallback(&msg);
  366. }
  367. String Script::GetCallStack(asIScriptContext* context)
  368. {
  369. String str("AngelScript callstack:\n");
  370. // Append the call stack
  371. for (asUINT i = 0; i < context->GetCallstackSize(); i++)
  372. {
  373. asIScriptFunction* func;
  374. const char* scriptSection;
  375. int line, column;
  376. func = context->GetFunction(i);
  377. line = context->GetLineNumber(i, &column, &scriptSection);
  378. str.AppendWithFormat("\t%s:%s:%d,%d\n", scriptSection, func->GetDeclaration(), line, column);
  379. }
  380. return str;
  381. }
  382. ScriptFile* Script::GetDefaultScriptFile() const
  383. {
  384. return defaultScriptFile_;
  385. }
  386. Scene* Script::GetDefaultScene() const
  387. {
  388. return defaultScene_;
  389. }
  390. void Script::ClearObjectTypeCache()
  391. {
  392. objectTypes_.Clear();
  393. }
  394. asIObjectType* Script::GetObjectType(const char* declaration)
  395. {
  396. HashMap<const char*, asIObjectType*>::ConstIterator i = objectTypes_.Find(declaration);
  397. if (i != objectTypes_.End())
  398. return i->second_;
  399. asIObjectType* type = scriptEngine_->GetObjectTypeById(scriptEngine_->GetTypeIdByDecl(declaration));
  400. objectTypes_[declaration] = type;
  401. return type;
  402. }
  403. asIScriptContext* Script::GetScriptFileContext()
  404. {
  405. while (scriptNestingLevel_ >= scriptFileContexts_.Size())
  406. {
  407. asIScriptContext* newContext = scriptEngine_->CreateContext();
  408. newContext->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  409. scriptFileContexts_.Push(newContext);
  410. }
  411. return scriptFileContexts_[scriptNestingLevel_];
  412. }
  413. void Script::OutputAPIRow(const String& row, bool removeReference)
  414. {
  415. String out = row;
  416. ///\todo We need Regex capability in String class to handle whole-word replacement correctly.
  417. // Temporary fix to prevent property name like 'doubleClickInterval' from being wrongly replaced.
  418. // Fortunately, there is no occurence of type 'double' in the API at the moment.
  419. //out.Replace("double", "float");
  420. out.Replace("&in", "&");
  421. out.Replace("&out", "&");
  422. if (removeReference)
  423. out.Replace("&", "");
  424. Log::WriteRaw("- " + out + "\n");
  425. }
  426. void Script::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  427. {
  428. using namespace ConsoleCommand;
  429. Execute(eventData[P_COMMAND].GetString());
  430. }
  431. void RegisterScriptLibrary(Context* context)
  432. {
  433. ScriptFile::RegisterObject(context);
  434. ScriptInstance::RegisterObject(context);
  435. }
  436. }