Script.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. //
  2. // Copyright (c) 2008-2017 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 "../AngelScript/Addons.h"
  24. #include "../AngelScript/Script.h"
  25. #include "../AngelScript/ScriptAPI.h"
  26. #include "../AngelScript/ScriptFile.h"
  27. #include "../AngelScript/ScriptInstance.h"
  28. #include "../Core/Profiler.h"
  29. #include "../Engine/EngineEvents.h"
  30. #include "../IO/FileSystem.h"
  31. #include "../IO/Log.h"
  32. #include "../Resource/ResourceCache.h"
  33. #include "../Scene/Scene.h"
  34. #include "../DebugNew.h"
  35. namespace Urho3D
  36. {
  37. class ScriptResourceRouter : public ResourceRouter
  38. {
  39. URHO3D_OBJECT(ScriptResourceRouter, ResourceRouter);
  40. /// Construct.
  41. ScriptResourceRouter(Context* context) :
  42. ResourceRouter(context)
  43. {
  44. }
  45. /// Check if request is for an AngelScript file and reroute to compiled version if necessary (.as file not available)
  46. void Route(String& name, ResourceRequest requestType) override
  47. {
  48. String extension = GetExtension(name);
  49. if (extension == ".as")
  50. {
  51. String replaced = ReplaceExtension(name, ".asc");
  52. // Note: ResourceCache prevents recursive calls to the resource routers so this is OK, the nested Exists()
  53. // check does not go through the router again
  54. auto* cache = GetSubsystem<ResourceCache>();
  55. if (!cache->Exists(name) && cache->Exists(replaced))
  56. name = replaced;
  57. }
  58. }
  59. };
  60. Script::Script(Context* context) :
  61. Object(context),
  62. scriptEngine_(nullptr),
  63. immediateContext_(nullptr),
  64. scriptNestingLevel_(0),
  65. executeConsoleCommands_(false)
  66. {
  67. scriptEngine_ = asCreateScriptEngine(ANGELSCRIPT_VERSION);
  68. if (!scriptEngine_)
  69. {
  70. URHO3D_LOGERROR("Could not create AngelScript engine");
  71. return;
  72. }
  73. scriptEngine_->SetUserData(this);
  74. scriptEngine_->SetEngineProperty(asEP_USE_CHARACTER_LITERALS, (asPWORD)true);
  75. scriptEngine_->SetEngineProperty(asEP_ALLOW_UNSAFE_REFERENCES, (asPWORD)true);
  76. scriptEngine_->SetEngineProperty(asEP_ALLOW_IMPLICIT_HANDLE_TYPES, (asPWORD)true);
  77. scriptEngine_->SetEngineProperty(asEP_BUILD_WITHOUT_LINE_CUES, (asPWORD)true);
  78. // Use the copy of the original asMETHOD macro in a web build (for some reason it still works, presumably because the signature of the function is known)
  79. #ifdef AS_MAX_PORTABILITY
  80. scriptEngine_->SetMessageCallback(_asMETHOD(Script, MessageCallback), this, asCALL_THISCALL);
  81. #else
  82. scriptEngine_->SetMessageCallback(asMETHOD(Script, MessageCallback), this, asCALL_THISCALL);
  83. #endif
  84. // Create the context for immediate execution
  85. immediateContext_ = scriptEngine_->CreateContext();
  86. // Use the copy of the original asMETHOD macro in a web build (for some reason it still works, presumably because the signature of the function is known)
  87. #ifdef AS_MAX_PORTABILITY
  88. immediateContext_->SetExceptionCallback(_asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  89. #else
  90. immediateContext_->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  91. #endif
  92. // Register Script library object factories
  93. RegisterScriptLibrary(context_);
  94. // Register the Array, String & Dictionary API
  95. RegisterArray(scriptEngine_);
  96. RegisterString(scriptEngine_);
  97. RegisterDictionary(scriptEngine_);
  98. RegisterScriptInterfaceAPI(scriptEngine_);
  99. // Register the rest of the script API
  100. RegisterMathAPI(scriptEngine_);
  101. RegisterCoreAPI(scriptEngine_);
  102. RegisterIOAPI(scriptEngine_);
  103. RegisterResourceAPI(scriptEngine_);
  104. RegisterSceneAPI(scriptEngine_);
  105. RegisterGraphicsAPI(scriptEngine_);
  106. RegisterInputAPI(scriptEngine_);
  107. RegisterAudioAPI(scriptEngine_);
  108. RegisterUIAPI(scriptEngine_);
  109. #ifdef URHO3D_NETWORK
  110. RegisterNetworkAPI(scriptEngine_);
  111. #endif
  112. #ifdef URHO3D_DATABASE
  113. RegisterDatabaseAPI(scriptEngine_);
  114. #endif
  115. #ifdef URHO3D_IK
  116. RegisterIKAPI(scriptEngine_);
  117. #endif
  118. #ifdef URHO3D_PHYSICS
  119. RegisterPhysicsAPI(scriptEngine_);
  120. #endif
  121. #ifdef URHO3D_NAVIGATION
  122. RegisterNavigationAPI(scriptEngine_);
  123. #endif
  124. #ifdef URHO3D_URHO2D
  125. RegisterUrho2DAPI(scriptEngine_);
  126. #endif
  127. RegisterScriptAPI(scriptEngine_);
  128. RegisterEngineAPI(scriptEngine_);
  129. // Subscribe to console commands
  130. SetExecuteConsoleCommands(true);
  131. // Create and register resource router for checking for compiled AngelScript files
  132. auto* cache = GetSubsystem<ResourceCache>();
  133. if (cache)
  134. {
  135. router_ = new ScriptResourceRouter(context_);
  136. cache->AddResourceRouter(router_);
  137. }
  138. }
  139. Script::~Script()
  140. {
  141. if (immediateContext_)
  142. {
  143. immediateContext_->Release();
  144. immediateContext_ = nullptr;
  145. }
  146. for (unsigned i = 0; i < scriptFileContexts_.Size(); ++i)
  147. scriptFileContexts_[i]->Release();
  148. if (scriptEngine_)
  149. {
  150. scriptEngine_->Release();
  151. scriptEngine_ = nullptr;
  152. }
  153. auto* cache = GetSubsystem<ResourceCache>();
  154. if (cache)
  155. cache->RemoveResourceRouter(router_);
  156. }
  157. bool Script::Execute(const String& line)
  158. {
  159. // Note: compiling code each time is slow. Not to be used for performance-critical or repeating activity
  160. URHO3D_PROFILE(ExecuteImmediate);
  161. ClearObjectTypeCache();
  162. String wrappedLine = "void f(){\n" + line + ";\n}";
  163. // If no immediate mode script file set, create a dummy module for compiling the line
  164. asIScriptModule* module = nullptr;
  165. if (defaultScriptFile_)
  166. module = defaultScriptFile_->GetScriptModule();
  167. if (!module)
  168. module = scriptEngine_->GetModule("ExecuteImmediate", asGM_CREATE_IF_NOT_EXISTS);
  169. if (!module)
  170. return false;
  171. asIScriptFunction* function = nullptr;
  172. if (module->CompileFunction("", wrappedLine.CString(), -1, 0, &function) < 0)
  173. return false;
  174. if (immediateContext_->Prepare(function) < 0)
  175. {
  176. function->Release();
  177. return false;
  178. }
  179. bool success = immediateContext_->Execute() >= 0;
  180. immediateContext_->Unprepare();
  181. function->Release();
  182. return success;
  183. }
  184. void Script::SetDefaultScriptFile(ScriptFile* file)
  185. {
  186. defaultScriptFile_ = file;
  187. }
  188. void Script::SetDefaultScene(Scene* scene)
  189. {
  190. defaultScene_ = scene;
  191. }
  192. void Script::SetExecuteConsoleCommands(bool enable)
  193. {
  194. if (enable == executeConsoleCommands_)
  195. return;
  196. executeConsoleCommands_ = enable;
  197. if (enable)
  198. SubscribeToEvent(E_CONSOLECOMMAND, URHO3D_HANDLER(Script, HandleConsoleCommand));
  199. else
  200. UnsubscribeFromEvent(E_CONSOLECOMMAND);
  201. }
  202. void Script::MessageCallback(const asSMessageInfo* msg)
  203. {
  204. String message;
  205. message.AppendWithFormat("%s:%d,%d %s", msg->section, msg->row, msg->col, msg->message);
  206. switch (msg->type)
  207. {
  208. case asMSGTYPE_ERROR:
  209. URHO3D_LOGERROR(message);
  210. break;
  211. case asMSGTYPE_WARNING:
  212. URHO3D_LOGWARNING(message);
  213. break;
  214. default:
  215. URHO3D_LOGINFO(message);
  216. break;
  217. }
  218. }
  219. void Script::ExceptionCallback(asIScriptContext* context)
  220. {
  221. String message;
  222. message.AppendWithFormat("- Exception '%s' in '%s'\n%s", context->GetExceptionString(),
  223. context->GetExceptionFunction()->GetDeclaration(), GetCallStack(context).CString());
  224. asSMessageInfo msg;
  225. msg.row = context->GetExceptionLineNumber(&msg.col, &msg.section);
  226. msg.type = asMSGTYPE_ERROR;
  227. msg.message = message.CString();
  228. MessageCallback(&msg);
  229. }
  230. String Script::GetCallStack(asIScriptContext* context)
  231. {
  232. String str("AngelScript callstack:\n");
  233. // Append the call stack
  234. for (asUINT i = 0; i < context->GetCallstackSize(); i++)
  235. {
  236. asIScriptFunction* func;
  237. const char* scriptSection;
  238. int line, column;
  239. func = context->GetFunction(i);
  240. line = context->GetLineNumber(i, &column, &scriptSection);
  241. str.AppendWithFormat("\t%s:%s:%d,%d\n", scriptSection, func->GetDeclaration(), line, column);
  242. }
  243. return str;
  244. }
  245. ScriptFile* Script::GetDefaultScriptFile() const
  246. {
  247. return defaultScriptFile_;
  248. }
  249. Scene* Script::GetDefaultScene() const
  250. {
  251. return defaultScene_;
  252. }
  253. void Script::ClearObjectTypeCache()
  254. {
  255. objectTypes_.Clear();
  256. }
  257. asITypeInfo* Script::GetObjectType(const char* declaration)
  258. {
  259. HashMap<const char*, asITypeInfo*>::ConstIterator i = objectTypes_.Find(declaration);
  260. if (i != objectTypes_.End())
  261. return i->second_;
  262. asITypeInfo* type = scriptEngine_->GetTypeInfoById(scriptEngine_->GetTypeIdByDecl(declaration));
  263. objectTypes_[declaration] = type;
  264. return type;
  265. }
  266. asIScriptContext* Script::GetScriptFileContext()
  267. {
  268. while (scriptNestingLevel_ >= scriptFileContexts_.Size())
  269. {
  270. asIScriptContext* newContext = scriptEngine_->CreateContext();
  271. // Use the copy of the original asMETHOD macro in a web build (for some reason it still works, presumably because the signature of the function is known)
  272. #ifdef AS_MAX_PORTABILITY
  273. newContext->SetExceptionCallback(_asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  274. #else
  275. newContext->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  276. #endif
  277. scriptFileContexts_.Push(newContext);
  278. }
  279. return scriptFileContexts_[scriptNestingLevel_];
  280. }
  281. void Script::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  282. {
  283. using namespace ConsoleCommand;
  284. if (eventData[P_ID].GetString() == GetTypeName())
  285. Execute(eventData[P_COMMAND].GetString());
  286. }
  287. void RegisterScriptLibrary(Context* context)
  288. {
  289. ScriptFile::RegisterObject(context);
  290. ScriptInstance::RegisterObject(context);
  291. }
  292. }