Script.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. //
  2. // Copyright (c) 2008-2015 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. virtual void Route(String& name, ResourceRequest requestType)
  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. ResourceCache* cache = GetSubsystem<ResourceCache>();
  55. if (!cache->Exists(name) && cache->Exists(replaced))
  56. name = replaced;
  57. }
  58. }
  59. };
  60. VariantMap Script::globalVars;
  61. Script::Script(Context* context) :
  62. Object(context),
  63. scriptEngine_(0),
  64. immediateContext_(0),
  65. scriptNestingLevel_(0),
  66. executeConsoleCommands_(false)
  67. {
  68. scriptEngine_ = asCreateScriptEngine(ANGELSCRIPT_VERSION);
  69. if (!scriptEngine_)
  70. {
  71. LOGERROR("Could not create AngelScript engine");
  72. return;
  73. }
  74. scriptEngine_->SetUserData(this);
  75. scriptEngine_->SetEngineProperty(asEP_USE_CHARACTER_LITERALS, (asPWORD)true);
  76. scriptEngine_->SetEngineProperty(asEP_ALLOW_UNSAFE_REFERENCES, (asPWORD)true);
  77. scriptEngine_->SetEngineProperty(asEP_ALLOW_IMPLICIT_HANDLE_TYPES, (asPWORD)true);
  78. scriptEngine_->SetEngineProperty(asEP_BUILD_WITHOUT_LINE_CUES, (asPWORD)true);
  79. scriptEngine_->SetMessageCallback(asMETHOD(Script, MessageCallback), this, asCALL_THISCALL);
  80. // Create the context for immediate execution
  81. immediateContext_ = scriptEngine_->CreateContext();
  82. immediateContext_->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  83. // Register Script library object factories
  84. RegisterScriptLibrary(context_);
  85. // Register the Array, String & Dictionary API
  86. RegisterArray(scriptEngine_);
  87. RegisterString(scriptEngine_);
  88. RegisterDictionary(scriptEngine_);
  89. RegisterScriptInterfaceAPI(scriptEngine_);
  90. // Register the rest of the script API
  91. RegisterMathAPI(scriptEngine_);
  92. RegisterCoreAPI(scriptEngine_);
  93. RegisterIOAPI(scriptEngine_);
  94. RegisterResourceAPI(scriptEngine_);
  95. RegisterSceneAPI(scriptEngine_);
  96. RegisterGraphicsAPI(scriptEngine_);
  97. RegisterInputAPI(scriptEngine_);
  98. RegisterAudioAPI(scriptEngine_);
  99. RegisterUIAPI(scriptEngine_);
  100. #ifdef URHO3D_NETWORK
  101. RegisterNetworkAPI(scriptEngine_);
  102. #endif
  103. #ifdef URHO3D_DATABASE
  104. RegisterDatabaseAPI(scriptEngine_);
  105. #endif
  106. #ifdef URHO3D_PHYSICS
  107. RegisterPhysicsAPI(scriptEngine_);
  108. #endif
  109. #ifdef URHO3D_NAVIGATION
  110. RegisterNavigationAPI(scriptEngine_);
  111. #endif
  112. #ifdef URHO3D_URHO2D
  113. RegisterUrho2DAPI(scriptEngine_);
  114. #endif
  115. RegisterScriptAPI(scriptEngine_);
  116. RegisterEngineAPI(scriptEngine_);
  117. // Subscribe to console commands
  118. SetExecuteConsoleCommands(true);
  119. // Create and register resource router for checking for compiled AngelScript files
  120. ResourceCache* cache = GetSubsystem<ResourceCache>();
  121. if (cache)
  122. {
  123. router_ = new ScriptResourceRouter(context_);
  124. cache->AddResourceRouter(router_);
  125. }
  126. }
  127. Script::~Script()
  128. {
  129. if (immediateContext_)
  130. {
  131. immediateContext_->Release();
  132. immediateContext_ = 0;
  133. }
  134. for (unsigned i = 0; i < scriptFileContexts_.Size(); ++i)
  135. scriptFileContexts_[i]->Release();
  136. if (scriptEngine_)
  137. {
  138. scriptEngine_->Release();
  139. scriptEngine_ = 0;
  140. }
  141. ResourceCache* cache = GetSubsystem<ResourceCache>();
  142. if (cache)
  143. cache->RemoveResourceRouter(router_);
  144. }
  145. bool Script::Execute(const String& line)
  146. {
  147. // Note: compiling code each time is slow. Not to be used for performance-critical or repeating activity
  148. PROFILE(ExecuteImmediate);
  149. ClearObjectTypeCache();
  150. String wrappedLine = "void f(){\n" + line + ";\n}";
  151. // If no immediate mode script file set, create a dummy module for compiling the line
  152. asIScriptModule* module = 0;
  153. if (defaultScriptFile_)
  154. module = defaultScriptFile_->GetScriptModule();
  155. if (!module)
  156. module = scriptEngine_->GetModule("ExecuteImmediate", asGM_CREATE_IF_NOT_EXISTS);
  157. if (!module)
  158. return false;
  159. asIScriptFunction* function = 0;
  160. if (module->CompileFunction("", wrappedLine.CString(), -1, 0, &function) < 0)
  161. return false;
  162. if (immediateContext_->Prepare(function) < 0)
  163. {
  164. function->Release();
  165. return false;
  166. }
  167. bool success = immediateContext_->Execute() >= 0;
  168. immediateContext_->Unprepare();
  169. function->Release();
  170. return success;
  171. }
  172. void Script::SetDefaultScriptFile(ScriptFile* file)
  173. {
  174. defaultScriptFile_ = file;
  175. }
  176. void Script::SetDefaultScene(Scene* scene)
  177. {
  178. defaultScene_ = scene;
  179. }
  180. void Script::SetExecuteConsoleCommands(bool enable)
  181. {
  182. if (enable == executeConsoleCommands_)
  183. return;
  184. executeConsoleCommands_ = enable;
  185. if (enable)
  186. SubscribeToEvent(E_CONSOLECOMMAND, URHO3D_HANDLER(Script, HandleConsoleCommand));
  187. else
  188. UnsubscribeFromEvent(E_CONSOLECOMMAND);
  189. }
  190. void Script::MessageCallback(const asSMessageInfo* msg)
  191. {
  192. String message;
  193. message.AppendWithFormat("%s:%d,%d %s", msg->section, msg->row, msg->col, msg->message);
  194. switch (msg->type)
  195. {
  196. case asMSGTYPE_ERROR:
  197. LOGERROR(message);
  198. break;
  199. case asMSGTYPE_WARNING:
  200. LOGWARNING(message);
  201. break;
  202. default:
  203. LOGINFO(message);
  204. break;
  205. }
  206. }
  207. void Script::ExceptionCallback(asIScriptContext* context)
  208. {
  209. String message;
  210. message.AppendWithFormat("- Exception '%s' in '%s'\n%s", context->GetExceptionString(),
  211. context->GetExceptionFunction()->GetDeclaration(), GetCallStack(context).CString());
  212. asSMessageInfo msg;
  213. msg.row = context->GetExceptionLineNumber(&msg.col, &msg.section);
  214. msg.type = asMSGTYPE_ERROR;
  215. msg.message = message.CString();
  216. MessageCallback(&msg);
  217. }
  218. String Script::GetCallStack(asIScriptContext* context)
  219. {
  220. String str("AngelScript callstack:\n");
  221. // Append the call stack
  222. for (asUINT i = 0; i < context->GetCallstackSize(); i++)
  223. {
  224. asIScriptFunction* func;
  225. const char* scriptSection;
  226. int line, column;
  227. func = context->GetFunction(i);
  228. line = context->GetLineNumber(i, &column, &scriptSection);
  229. str.AppendWithFormat("\t%s:%s:%d,%d\n", scriptSection, func->GetDeclaration(), line, column);
  230. }
  231. return str;
  232. }
  233. ScriptFile* Script::GetDefaultScriptFile() const
  234. {
  235. return defaultScriptFile_;
  236. }
  237. Scene* Script::GetDefaultScene() const
  238. {
  239. return defaultScene_;
  240. }
  241. void Script::ClearObjectTypeCache()
  242. {
  243. objectTypes_.Clear();
  244. }
  245. asIObjectType* Script::GetObjectType(const char* declaration)
  246. {
  247. HashMap<const char*, asIObjectType*>::ConstIterator i = objectTypes_.Find(declaration);
  248. if (i != objectTypes_.End())
  249. return i->second_;
  250. asIObjectType* type = scriptEngine_->GetObjectTypeById(scriptEngine_->GetTypeIdByDecl(declaration));
  251. objectTypes_[declaration] = type;
  252. return type;
  253. }
  254. asIScriptContext* Script::GetScriptFileContext()
  255. {
  256. while (scriptNestingLevel_ >= scriptFileContexts_.Size())
  257. {
  258. asIScriptContext* newContext = scriptEngine_->CreateContext();
  259. newContext->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  260. scriptFileContexts_.Push(newContext);
  261. }
  262. return scriptFileContexts_[scriptNestingLevel_];
  263. }
  264. void Script::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  265. {
  266. using namespace ConsoleCommand;
  267. if (eventData[P_ID].GetString() == GetTypeName())
  268. Execute(eventData[P_COMMAND].GetString());
  269. }
  270. void RegisterScriptLibrary(Context* context)
  271. {
  272. ScriptFile::RegisterObject(context);
  273. ScriptInstance::RegisterObject(context);
  274. }
  275. }