Script.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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. scriptNestingLevel_(0)
  129. {
  130. scriptEngine_ = asCreateScriptEngine(ANGELSCRIPT_VERSION);
  131. if (!scriptEngine_)
  132. {
  133. LOGERROR("Could not create AngelScript engine");
  134. return;
  135. }
  136. scriptEngine_->SetUserData(this);
  137. scriptEngine_->SetEngineProperty(asEP_USE_CHARACTER_LITERALS, true);
  138. scriptEngine_->SetEngineProperty(asEP_ALLOW_UNSAFE_REFERENCES, true);
  139. scriptEngine_->SetEngineProperty(asEP_ALLOW_IMPLICIT_HANDLE_TYPES, true);
  140. scriptEngine_->SetEngineProperty(asEP_BUILD_WITHOUT_LINE_CUES, true);
  141. scriptEngine_->SetMessageCallback(asMETHOD(Script, MessageCallback), this, asCALL_THISCALL);
  142. // Create the context for immediate execution
  143. immediateContext_ = scriptEngine_->CreateContext();
  144. immediateContext_->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  145. // Register Script library object factories
  146. RegisterScriptLibrary(context_);
  147. // Register the Array, String & Dictionary API
  148. RegisterArray(scriptEngine_);
  149. RegisterString(scriptEngine_);
  150. RegisterDictionary(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::DumpAPI(DumpMode mode)
  220. {
  221. // Does not use LOGRAW macro here to ensure the messages are always dumped regardless of ENABLE_LOGGING compiler directive and of Log subsystem availability
  222. if (mode == DOXYGEN)
  223. Log::WriteRaw("namespace Urho3D\n{\n\n/**\n\\page ScriptAPI Scripting API\n\n");
  224. else if (mode == C_HEADER)
  225. Log::WriteRaw("// Script API header intended to be 'force included' in IDE for AngelScript content assist / code completion\n\n"
  226. "#define int8 signed char\n"
  227. "#define int16 signed short\n"
  228. "#define int64 long\n"
  229. "#define uint8 unsigned char\n"
  230. "#define uint16 unsigned short\n"
  231. "#define uint64 unsigned long\n"
  232. "#define null 0\n");
  233. if (mode == DOXYGEN)
  234. Log::WriteRaw("\\section ScriptAPI_Enums Enumerations\n");
  235. else if (mode == C_HEADER)
  236. Log::WriteRaw("\n// Enumerations\n");
  237. unsigned enums = scriptEngine_->GetEnumCount();
  238. for (unsigned i = 0; i < enums; ++i)
  239. {
  240. int typeId;
  241. if (mode == DOXYGEN)
  242. Log::WriteRaw("\n### " + String(scriptEngine_->GetEnumByIndex(i, &typeId)) + "\n\n");
  243. else if (mode == C_HEADER)
  244. Log::WriteRaw("\nenum " + String(scriptEngine_->GetEnumByIndex(i, &typeId)) + "\n{\n");
  245. for (unsigned j = 0; j < (unsigned)scriptEngine_->GetEnumValueCount(typeId); ++j)
  246. {
  247. int value = 0;
  248. const char* name = scriptEngine_->GetEnumValueByIndex(typeId, j, &value);
  249. OutputAPIRow(mode, String(name), false, ",");
  250. }
  251. if (mode == DOXYGEN)
  252. Log::WriteRaw("\n");
  253. else if (mode == C_HEADER)
  254. Log::WriteRaw("};\n");
  255. }
  256. if (mode == DOXYGEN)
  257. Log::WriteRaw("\\section ScriptAPI_Classes Classes\n");
  258. else if (mode == C_HEADER)
  259. Log::WriteRaw("\n// Classes\n");
  260. unsigned types = scriptEngine_->GetObjectTypeCount();
  261. for (unsigned i = 0; i < types; ++i)
  262. {
  263. asIObjectType* type = scriptEngine_->GetObjectTypeByIndex(i);
  264. if (type)
  265. {
  266. String typeName(type->GetName());
  267. Vector<String> methodDeclarations;
  268. Vector<PropertyInfo> propertyInfos;
  269. if (mode == DOXYGEN)
  270. Log::WriteRaw("\n### " + typeName + "\n");
  271. else if (mode == C_HEADER)
  272. {
  273. ///\todo Find a cleaner way to do this instead of hardcoding
  274. if (typeName == "Array")
  275. Log::WriteRaw("\ntemplate <class T> class " + typeName + "\n{\n");
  276. else
  277. Log::WriteRaw("\nclass " + typeName + "\n{\n");
  278. }
  279. unsigned methods = type->GetMethodCount();
  280. for (unsigned j = 0; j < methods; ++j)
  281. {
  282. asIScriptFunction* method = type->GetMethodByIndex(j);
  283. String methodName(method->GetName());
  284. String declaration(method->GetDeclaration());
  285. if (methodName.Contains("get_") || methodName.Contains("set_"))
  286. ExtractPropertyInfo(methodName, declaration, propertyInfos);
  287. else
  288. {
  289. // Sanitate the method name. \todo For now, skip the operators
  290. if (!declaration.Contains("::op"))
  291. {
  292. String prefix(typeName + "::");
  293. declaration.Replace(prefix, "");
  294. methodDeclarations.Push(declaration);
  295. }
  296. }
  297. }
  298. // Assume that the same property is never both an accessor property, and a direct one
  299. unsigned properties = type->GetPropertyCount();
  300. for (unsigned j = 0; j < properties; ++j)
  301. {
  302. const char* propertyName;
  303. const char* propertyDeclaration;
  304. int typeId;
  305. type->GetProperty(j, &propertyName, &typeId);
  306. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  307. PropertyInfo newInfo;
  308. newInfo.name_ = String(propertyName);
  309. newInfo.type_ = String(propertyDeclaration);
  310. newInfo.read_ = newInfo.write_ = true;
  311. propertyInfos.Push(newInfo);
  312. }
  313. if (!methodDeclarations.Empty())
  314. {
  315. if (mode == DOXYGEN)
  316. Log::WriteRaw("\nMethods:\n\n");
  317. else if (mode == C_HEADER)
  318. Log::WriteRaw("// Methods:\n");
  319. for (unsigned j = 0; j < methodDeclarations.Size(); ++j)
  320. OutputAPIRow(mode, methodDeclarations[j]);
  321. }
  322. if (!propertyInfos.Empty())
  323. {
  324. if (mode == DOXYGEN)
  325. Log::WriteRaw("\nProperties:\n\n");
  326. else if (mode == C_HEADER)
  327. Log::WriteRaw("\n// Properties:\n");
  328. for (unsigned j = 0; j < propertyInfos.Size(); ++j)
  329. {
  330. String remark;
  331. String cppdoc;
  332. if (!propertyInfos[j].write_)
  333. remark = " (readonly)";
  334. else if (!propertyInfos[j].read_)
  335. remark = " (writeonly)";
  336. if (mode == C_HEADER && !remark.Empty())
  337. {
  338. cppdoc = "/*" + remark + " */\n";
  339. remark.Clear();
  340. }
  341. OutputAPIRow(mode, cppdoc + propertyInfos[j].type_ + " " + propertyInfos[j].name_ + remark);
  342. }
  343. }
  344. if (mode == DOXYGEN)
  345. Log::WriteRaw("\n");
  346. else if (mode == C_HEADER)
  347. Log::WriteRaw("};\n");
  348. }
  349. }
  350. Vector<PropertyInfo> globalPropertyInfos;
  351. Vector<String> globalFunctions;
  352. unsigned functions = scriptEngine_->GetGlobalFunctionCount();
  353. for (unsigned i = 0; i < functions; ++i)
  354. {
  355. asIScriptFunction* function = scriptEngine_->GetGlobalFunctionByIndex(i);
  356. String functionName(function->GetName());
  357. String declaration(function->GetDeclaration());
  358. if (functionName.Contains("set_") || functionName.Contains("get_"))
  359. ExtractPropertyInfo(functionName, declaration, globalPropertyInfos);
  360. else
  361. globalFunctions.Push(declaration);
  362. }
  363. if (mode == DOXYGEN)
  364. Log::WriteRaw("\\section ScriptAPI_GlobalFunctions Global functions\n");
  365. else if (mode == C_HEADER)
  366. Log::WriteRaw("\n// Global functions\n");
  367. for (unsigned i = 0; i < globalFunctions.Size(); ++i)
  368. OutputAPIRow(mode, globalFunctions[i]);
  369. if (mode == DOXYGEN)
  370. Log::WriteRaw("\\section ScriptAPI_GlobalProperties Global properties\n");
  371. else if (mode == C_HEADER)
  372. Log::WriteRaw("\n// Global properties\n");
  373. for (unsigned i = 0; i < globalPropertyInfos.Size(); ++i)
  374. OutputAPIRow(mode, globalPropertyInfos[i].type_ + " " + globalPropertyInfos[i].name_, true);
  375. if (mode == DOXYGEN)
  376. Log::WriteRaw("\\section ScriptAPI_GlobalConstants Global constants\n");
  377. else if (mode == C_HEADER)
  378. Log::WriteRaw("\n// Global constants\n");
  379. unsigned properties = scriptEngine_->GetGlobalPropertyCount();
  380. for (unsigned i = 0; i < properties; ++i)
  381. {
  382. const char* propertyName;
  383. const char* propertyDeclaration;
  384. int typeId;
  385. scriptEngine_->GetGlobalPropertyByIndex(i, &propertyName, 0, &typeId);
  386. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  387. String type(propertyDeclaration);
  388. OutputAPIRow(mode, type + " " + String(propertyName), true);
  389. }
  390. if (mode == DOXYGEN)
  391. Log::WriteRaw("*/\n\n}\n");
  392. }
  393. void Script::MessageCallback(const asSMessageInfo* msg)
  394. {
  395. String message;
  396. message.AppendWithFormat("%s:%d,%d %s", msg->section, msg->row, msg->col, msg->message);
  397. switch (msg->type)
  398. {
  399. case asMSGTYPE_ERROR:
  400. LOGERROR(message);
  401. break;
  402. case asMSGTYPE_WARNING:
  403. LOGWARNING(message);
  404. break;
  405. default:
  406. LOGINFO(message);
  407. break;
  408. }
  409. }
  410. void Script::ExceptionCallback(asIScriptContext* context)
  411. {
  412. String message;
  413. message.AppendWithFormat("- Exception '%s' in '%s'\n%s", context->GetExceptionString(), context->GetExceptionFunction()->GetDeclaration(), GetCallStack(context).CString());
  414. asSMessageInfo msg;
  415. msg.row = context->GetExceptionLineNumber(&msg.col, &msg.section);
  416. msg.type = asMSGTYPE_ERROR;
  417. msg.message = message.CString();
  418. MessageCallback(&msg);
  419. }
  420. String Script::GetCallStack(asIScriptContext* context)
  421. {
  422. String str("AngelScript callstack:\n");
  423. // Append the call stack
  424. for (asUINT i = 0; i < context->GetCallstackSize(); i++)
  425. {
  426. asIScriptFunction* func;
  427. const char* scriptSection;
  428. int line, column;
  429. func = context->GetFunction(i);
  430. line = context->GetLineNumber(i, &column, &scriptSection);
  431. str.AppendWithFormat("\t%s:%s:%d,%d\n", scriptSection, func->GetDeclaration(), line, column);
  432. }
  433. return str;
  434. }
  435. ScriptFile* Script::GetDefaultScriptFile() const
  436. {
  437. return defaultScriptFile_;
  438. }
  439. Scene* Script::GetDefaultScene() const
  440. {
  441. return defaultScene_;
  442. }
  443. void Script::ClearObjectTypeCache()
  444. {
  445. objectTypes_.Clear();
  446. }
  447. asIObjectType* Script::GetObjectType(const char* declaration)
  448. {
  449. HashMap<const char*, asIObjectType*>::ConstIterator i = objectTypes_.Find(declaration);
  450. if (i != objectTypes_.End())
  451. return i->second_;
  452. asIObjectType* type = scriptEngine_->GetObjectTypeById(scriptEngine_->GetTypeIdByDecl(declaration));
  453. objectTypes_[declaration] = type;
  454. return type;
  455. }
  456. asIScriptContext* Script::GetScriptFileContext()
  457. {
  458. while (scriptNestingLevel_ >= scriptFileContexts_.Size())
  459. {
  460. asIScriptContext* newContext = scriptEngine_->CreateContext();
  461. newContext->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  462. scriptFileContexts_.Push(newContext);
  463. }
  464. return scriptFileContexts_[scriptNestingLevel_];
  465. }
  466. void Script::OutputAPIRow(DumpMode mode, const String& row, bool removeReference, String separator)
  467. {
  468. String out(row);
  469. ///\todo We need C++11 <regex> in String class to handle REGEX whole-word replacement correctly. Can't do that since we still support VS2008.
  470. // Commenting out to temporary fix property name like 'doubleClickInterval' from being wrongly replaced.
  471. // Fortunately, there is no occurence of type 'double' in the API at the moment.
  472. //out.Replace("double", "float"); // s/\bdouble\b/float/g
  473. out.Replace("&in", "&");
  474. out.Replace("&out", "&");
  475. if (removeReference)
  476. out.Replace("&", "");
  477. if (mode == DOXYGEN)
  478. Log::WriteRaw("- " + out + "\n");
  479. else if (mode == C_HEADER)
  480. {
  481. out.Replace("@", "");
  482. out.Replace("?&", "void*");
  483. // s/(\w+)\[\]/Array<\1>/g
  484. unsigned posBegin = String::NPOS;
  485. while (1) // Loop to cater for array of array of T
  486. {
  487. unsigned posEnd = out.Find("[]");
  488. if (posEnd == String::NPOS)
  489. break;
  490. if (posBegin > posEnd)
  491. posBegin = posEnd - 1;
  492. while (posBegin < posEnd && isalnum(out[posBegin]))
  493. --posBegin;
  494. ++posBegin;
  495. out.Replace(posBegin, posEnd - posBegin + 2, "Array<" + out.Substring(posBegin, posEnd - posBegin) + ">");
  496. }
  497. Log::WriteRaw(out + separator + "\n");
  498. }
  499. }
  500. void Script::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  501. {
  502. using namespace ConsoleCommand;
  503. Execute(eventData[P_COMMAND].GetString());
  504. }
  505. void RegisterScriptLibrary(Context* context)
  506. {
  507. ScriptFile::RegisterObject(context);
  508. ScriptInstance::RegisterObject(context);
  509. }
  510. }